問題描述
Python 中的整數(shù)存儲在二進(jìn)制補碼中,對嗎?
Integers in Python are stored in two's complement, correct?
雖然:
>>> x = 5
>>> bin(x)
0b101
還有:
>>> x = -5
>>> bin(x)
-0b101
這很蹩腳.如何讓 python 給我 REAL 二進(jìn)制位的數(shù)字,并且前面沒有 0b?所以:
That's pretty lame. How do I get python to give me the numbers in REAL binary bits, and without the 0b infront of it? So:
>>> x = 5
>>> bin(x)
0101
>>> y = -5
>>> bin(y)
1011
推薦答案
不確定如何使用標(biāo)準(zhǔn)庫獲得所需的內(nèi)容.有一些腳本和包可以為您進(jìn)行轉(zhuǎn)換.
Not sure how to get what you want using the standard lib. There are a handful of scripts and packages out there that will do the conversion for you.
我只是想說明為什么",以及為什么它不蹩腳.
I just wanted to note the "why" , and why it's not lame.
bin() 不返回二進(jìn)制位.它將數(shù)字轉(zhuǎn)換為二進(jìn)制字符串.根據(jù) python 語言定義,前導(dǎo) '0b' 告訴解釋器您正在處理二進(jìn)制數(shù).這樣你就可以直接使用二進(jìn)制數(shù),就像這樣
bin() doesn't return binary bits. it converts the number to a binary string. the leading '0b' tells the interpreter that you're dealing with a binary number , as per the python language definition. this way you can directly work with binary numbers, like this
>>> 0b01
1
>>> 0b10
2
>>> 0b11
3
>>> 0b01 + 0b10
3
這不是蹩腳的.太好了.
that's not lame. that's great.
http://docs.python.org/library/functions.html#bin
bin(x)
將整數(shù)轉(zhuǎn)換為二進(jìn)制字符串.
Convert an integer number to a binary string.
http://docs.python.org/reference/lexical_analysis.html#integers
整數(shù)和長整數(shù)文字由以下詞法定義描述:
Integer and long integer literals are described by the following lexical definitions:
bininteger ::= "0" ("b" | "B") bindigit+
bininteger ::= "0" ("b" | "B") bindigit+
bindigit ::= "0" |1"
bindigit ::= "0" | "1"
這篇關(guān)于Python中的二進(jìn)制補碼?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!