如何解决有符号整数的最低有效位 (LSB) 的否定
This 答案演示了整数 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。为什么 c
和 d
的实际值与其预期值不匹配?
解决方法
我认为这里的问题是python将负数存储为它们的二进制补码,但不会以这种方式打印出来。让事情变得非常混乱!这篇文章here goes into more detail about it,但我们可以通过一个简单的例子来了解发生了什么:
-4 在二进制中是 0b11111100(4 的二进制补码)
1 是正数,所以在二进制中它只是 0b00000001
当你或那两个在一起时,你会得到:
0b11111101 是 -3(二进制补码)的二进制表示
I used this site 找到二进制补码,值得注意的是python整数是32位而不是8位,所以负数/二进制补码前面会有24个额外的1和24个额外的0正数的前面(只要两者都低于 abs(255))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。