python - 有符号整数的最低有效位 (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))
c
LSB 取反后的期望值为 -5 而不是 -3。同样,LSB取反后的期望值d
为-4而不是-6。为什么实际值c
和d
预期值不匹配?
解决方案
我认为这里的问题是 python 将负数存储为它们的补码,但不会以这种方式打印出来。让事情变得非常混乱!这篇文章在这里更详细地介绍了它,但我们可以通过一个简单的例子来了解发生了什么:
二进制中的 -4 是 0b11111100(4 的补码)
1 是正数,所以在二进制中它只是 0b00000001
当你或这两个人在一起时,你会得到:
0b11111101 是 -3 的二进制表示(二进制补码)
我用这个网站找到了二进制补码,值得注意的是python整数是32位而不是8位,所以在负数/二进制补码前会有24个额外的1,在正数前会有24个额外的0 (只要两者都低于 abs(255))
推荐阅读
- python - Python获取给定年份的月份开始日期和结束日期
- r - 如何删除R中的重复行?
- .net - LINQ 通过用户选择获取带有计数的搜索选项
- java - JSON对象数组到pojo
- unity3d - LineRenderer 将端盖顶点置于错误的方向
- javascript - JavaScript 识别页面是 RTL 还是 LTR?
- r - 按国家/地区划分变量的箱线图函数
- c# - 如何突出显示从外部源向 Microsoft Teams 活动源发送通知的消息
- swiftui - 如何在没有 SceneDelegate 的情况下在 SwiftUI 中设置 EnvironmentObject?
- hadoop - 如何仅获取昨天的纱线完成/失败工作列表