有符号整数的最低有效位(LSB)的取反



这个答案演示了整数的LSB的否定。当使用负(有符号(整数时,这种方法不会产生预期的结果。让我们看看一些代码:

a = 4
print()
print("a: " + str(a))
print("binary version of a: " + bin(a))
a = a | 1
print("binary version of a after negation of LSB: " + bin(a))
print("a after negation of LSB: " + str(a))
print()
b = 5
print("b: " + str(b))
print("binary version of b: " + bin(b))
b = b & ~1
print("binary version of b after negation of LSB: " + bin(b))
print("b after negation of LSB: " + str(b))
print()
c = -4
print("c: " + str(c))
print("binary version of c: " + bin(c))
c = c | 1
print("binary version of c after negation of LSB: " + bin(c))
print("c after negation of LSB: " + str(c))
print()
d = -5
print("d: " + str(d))
print("binary version of d: " + bin(d))
d = d & ~1
print("binary version of d after negation of LSB: " + bin(d))
print("d after negation of LSB: " + str(d))

在LSB的否定之后,c的期望值是-5而不是-3。类似地,在LSB的否定之后d的期望值是-4而不是-6。为什么cd的实际值与预期值不匹配?

我认为这里的问题是python将负数存储为其二的补码,但不以这种方式打印出来。让事情变得很混乱!这篇文章更详细地介绍了它,但我们可以通过一个快速的例子来看看发生了什么:

-二进制中的4是0b11111100(4的二补码(

1是正的,所以在二进制中它只是0b00000001

当你或这两个人在一起时,你会得到:

0b11111101,它是-3(二的补码(的二进制表示

我用这个网站来寻找二者的补码,值得注意的是,python整数是32位,而不是8位,所以在负数/二者的补数前面会有24个额外的1,在正数前面会有20个额外的0(只要两者都低于abs(255((

最新更新