位非运算符不会翻转位。

huangapple go评论140阅读模式
英文:

Bitwise not operator doesn't flip bits

问题

我正在尝试使用位非运算符来翻转1中的位。我从1 (00000001) 开始,然后加上 ~。

x = ~1
print(f'{x:08b}')

结果是 -0000010。

所有在线信息都告诉我结果应该是 11111110。不确定在数字前面加 ~ 时我可能出了什么问题。

我尝试添加了一个步骤,以确保1显示为 00000001,它成功了:

a = 1
print(f'{a:08b}')
x = ~a
print(f'{x:08b}')

真的不确定我在哪里出错了...

英文:

I am trying to use the bitwise not operator to flip the bits in 1.

I start with 1 (00000001) and add ~.

x = ~1
print(f'{x:08b}')

Result is -0000010.

Everything online tells me the result should be 11111110. Not sure what I can do wrong with putting ~ in front of a number.

I tried adding a step to make sure 1 shows up as 00000001, and it did:

a = 1
print(f'{a:08b}')
x = ~a
print(f'{x:08b}')

Really not sure how I can go wrong on this...

答案1

得分: 2

"The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1)."
"所以它的行为如预期,打印出“正数的2的补码的负数”。它不会打印出2的补码的负数,因为:https://stackoverflow.com/questions/16255496/format-negative-integers-in-twos-complement-representation"

英文:

https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations

> The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1).

So it's behaving as expected, printing "negative-of-a positive 2's complement". It doesn't print in 2's complement negative because: https://stackoverflow.com/questions/16255496/format-negative-integers-in-twos-complement-representation

huangapple
  • 本文由 发表于 2023年5月11日 04:00:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定