Python中的Two补码

2024-09-28 03:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

python中是否有内置函数将二进制字符串(例如“111111111”)转换为two's complement integer-1?


Tags: 函数字符串二进制integer内置twocomplement
3条回答

它不是内置的,但是如果您想要不寻常的长度数字,那么可以使用bitstring模块。

>>> from bitstring import Bits
>>> a = Bits(bin='111111111111')
>>> a.int
-1

同一个对象可以通过几种方式等效地创建,包括

>>> b = Bits(int=-1, length=12)

它的行为就像一个任意长度的位字符串,并使用属性获得不同的解释:

>>> print a.int, a.uint, a.bin, a.hex, a.oct
-1 4095 111111111111 fff 7777

自Python 3.2以来,就有了用于字节操作的内置函数:https://docs.python.org/3.4/library/stdtypes.html#int.to_bytes

通过组合到字节和从字节,可以得到

def twos(val_str, bytes):
    import sys
    val = int(val_str, 2)
    b = val.to_bytes(bytes, byteorder=sys.byteorder, signed=False)                                                          
    return int.from_bytes(b, byteorder=sys.byteorder, signed=True)

检查:

twos('11111111', 1)  # gives -1
twos('01111111', 1)  # gives 127

对于较旧版本的Python,travc的答案是好的,但如果希望使用整数而不是字符串,则它不适用于负值。对于f(f(val))==val的twos补码函数,每个val为:

def twos_complement(val, nbits):
    """Compute the 2's complement of int value val"""
    if val < 0:
        val = (1 << nbits) + val
    else:
        if (val & (1 << (nbits - 1))) != 0:
            # If sign bit is set.
            # compute negative value.
            val = val - (1 << nbits)
    return val

如果最高位是1,则2的补码减去(1<<bits)。以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)

相关问题 更多 >

    热门问题