首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对有符号整数的最低有效位(LSB)求反

对有符号整数的最低有效位(LSB)求反
EN

Stack Overflow用户
提问于 2021-06-22 22:07:46
回答 1查看 98关注 0票数 1

LSB answer演示了整数的This求反。当使用负(有符号)整数时,这种方法不会产生预期的结果。让我们看一些代码:

代码语言:javascript
复制
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的期望值是-5,而不是-3。类似地,取反后d的期望值是-4,而不是-6。为什么cd的实际值与预期值不匹配?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-22 22:22:29

我认为这里的问题是python将负数存储为两个数的补码,但不会以这种方式打印出来。让事情变得非常混乱!这篇文章是here goes into more detail about it的,但是我们可以通过一个简单的例子来看看发生了什么:

二进制是-4 \f25 0b11111100 -4\f6(-4\f25 4-4\f6的二进制补码)

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

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

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

used this site来找两个的补码,值得注意的是,python整数是32位而不是8位,所以在负数/2的补数前面有24个额外的1,在正数前面有24个额外的0(只要两者都低于abs(255))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68085086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档