python - Python中的二进制补码

标签 python bit-manipulation twos-complement

python中是否有一个内置函数可以将二进制字符串(例如'111111111111')转换为two's complement integer -1?

最佳答案

二进制补码减去 (1<<bits)如果最高位是 1。以 8 位为例,这给出的范围是 127 到 -128。

整数补码的函数...

def twos_comp(val, bits):
    """compute the 2's complement of int value val"""
    if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
        val = val - (1 << bits)        # compute negative value
    return val                         # return positive value as is

从二进制字符串开始特别容易...

binary_string = '1111' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))

对我来说更有用的是十六进制值(本例中为 32 位)...

hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter
out = twos_comp(int(hex_string,16), 32)

关于python - Python中的二进制补码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1604464/

相关文章:

javascript - JS : Why is ~10 (binary, ~1010) = -11 (二进制, -1011)?

Python 脚本通过 ssh 连接、运行进程并断开连接,无需等待

python - Tweepy:带有 'Bad Authentication data' 错误的简单脚本

PHP Left Shift 在两台不同的机器上给出两个答案

vhdl - 如何在不使用加法器的情况下制作数字的 2 补码

c - C 中无符号变量的算术运算

python - 如何在枕头中使用 alpha_composite?

python - 如果 py.test 从另一个目录执行它,coverage.py 不会覆盖脚本

c++ - 将整数乘以适当分数的快速方法,无需 float 或溢出

c - 奇偶校验如何找到偶数或奇数 1 的位?