問題描述
Bitwise NOT 是第一個補碼,例如:
Bitwise NOT is the first complement, for example:
x = 1
(二進制:0001)~x = -2
(二進制:1110)
x = 1
(binary: 0001)~x = -2
(binary: 1110)
因此,我的問題是為什么二進制中的 -2 是 (-0b10) 與 python 編譯器一樣?
Hence, my question is why -2 in binary is (-0b10) as for the python compiler?
我們知道 1110 表示 (14) 代表無符號整數和 (-2) 代表有符號整數.
We know that 1110 represents (14) for unsigned integer and (-2) for signed integer.
推薦答案
二進制補碼本質上取決于數字的大小.例如,有符號 4 位上的 -2 是 1110
,但有符號 8 位上是 1111 1110
.
Two's complement inherently depends on the size of a number. For example, -2 on signed 4-bit is 1110
but on signed 8-bit is 1111 1110
.
Python 的整數類型是任意精度的.這意味著沒有明確定義的前導位來指示負號或二進制補碼的明確長度.二進制補碼是 1...1110
,其中 ...
是 1
的無限重復.
Python's integer type is arbitrary precision. That means there is no well-defined leading bit to indicate negative sign or well-defined length of the two's complement. A two's complement would be 1... 1110
, where ...
is an infinite repetition of 1
.
因此,Python 的整數顯示為單獨的符號(無或-
)和絕對數字.因此,-2
變為 -
和 0b10
- 即 -
2
.同樣,-5
變成 -
和 0b101
——即 -
5
.
As such, Python's integer are displayed as a separate sign (nothing or -
) and the absolute number. Thus, -2
becomes -
and 0b10
– i.e. -
2
. Similarly, -5
becomes -
and 0b101
– i.e. -
5
.
請注意,此表示只是人類可讀的標準表示.它不一定是實現定義的內部表示.
Note that this representation is merely the standard representation to be human-readable. It is not necessarily the internal representation, which is implementation defined.
這篇關于為什么二進制表示與 python 編譯器不同,而不是我們在紙上所知道的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!