python 中的按位运算和补码

bitwise operation and Two's complement in python

我有一个(短)数据数组,它向左移动了 4 位,它也是一个有符号数。我需要将它绘制在零附近。

例如:如果数组中的数字是 0b0000000011111111,我将它向左移动 4,我将得到 0b000000001111。没事。

例如:如果数组中的数字是 0b100011111111,我将它向左移动 4,我将得到 0b000010001111。还好,现在不是负数了

有人可以帮忙吗?

这不会发生在 Python:

>>> bin(0b0000000011111111 >> 4)  # 15
'0b1111'
>>> bin(0b100011111111 >> 4)  # 143
'0b10001111'

顺便说一句,你作为负短整数的例子显示的数字不是一,因为你只给了12位。所以我会假设感兴趣的数量是0b1000000011111111。由于Python不使用2的补码,所以显示为33023。但是你可以用手做 2 的补码 :对于 short int(16 位),你只需将数字减去 0x10000。

然后你可以写:

def short_signed_right_shift(x, i):
    if x < 0 or x >= 0x10000: raise ValueError   # only accept 16 bits numbers
    return x >> i if (x < 0x7FFF) else 0x10000 + ((x - 0x10000) >> i)

然后您就可以使用它了:

>>> bin(short_signed_right_shift(0b0000000011111111, 4))
'0b1111'
>>> bin(short_signed_right_shift(0b1000000011111111, 4))
'0b1111100000001111'

如果需要,您必须自己编写 16 位值算术右移的实现。我建议你这个,很容易理解:

def arithmetic_right_shift_on_16_bits(val, n):
    # Get the sign bit
    s = val & 0x8000
    # Perform the shifts, padding with the sign bit
    for _ in range(n):
        val >>= 1
        val |= s
    return val

a = arithmetic_right_shift_on_16_bits(0b0000000011111111, 4)
print(bin(a)) # 0b1111

b = arithmetic_right_shift_on_16_bits(0b1000000011111111, 4)
print(bin(b)) # 0b1111100000001111