Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 蟒蛇3:~2=-0b11?_Python_Python 3.x_Bit Manipulation_Bitwise Operators - Fatal编程技术网

Python 蟒蛇3:~2=-0b11?

Python 蟒蛇3:~2=-0b11?,python,python-3.x,bit-manipulation,bitwise-operators,Python,Python 3.x,Bit Manipulation,Bitwise Operators,在python3中运行以下命令 >>> print(2, bin(2), ~2, bin(~2)) > 2 0b10 -3 -0b11 我想~2应该是0b01或0b101 为什么-0b11?首先看~2: 2 = 0b0000...10 (n leading 0s) ~2 = 0b1111...01 (n leading 1s) 然后分析-0b11 大多数计算机数字表示使用两个补码表示法,其中: A - B = A + ~B + 1 因此-0b11实际上是: -

在python3中运行以下命令

>>> print(2, bin(2), ~2, bin(~2))
> 2 0b10 -3 -0b11
我想~2应该是0b01或0b101

为什么-0b11?

首先看~2:

 2 = 0b0000...10 (n leading 0s)
~2 = 0b1111...01 (n leading 1s)
然后分析-0b11

大多数计算机数字表示使用两个补码表示法,其中:

A - B = A + ~B + 1
因此-0b11实际上是:

  - 0b11
= 0 - 0b11
= 0b0000...00 + 0b1111...00 + 1
= 0b1111...01
二的补码中11111101的值是多少

要回答这个问题,请遵循以下简单算法:

翻转所有位 将1添加到结果中 根据MSB确定符号 请注意,最高有效位为1,因此符号为负数。

关于0x111…01,您的意思是0b111…01吗?
 2  = 00000010
~2  = 11111101
11111101 > 00000010 > 00000011 
         ^          ^ 
       Flip       Add 1