二进制补码在Python? [英] Two's Complement Binary in Python?
问题描述
在Python整数储存在两个补,是否正确?
虽然
>>> X = 5
>>>斌(X)
0b101时
和
>>> X = -5
>>>斌(X)
-0b101
这是pretty跛。我如何获得蟒蛇给我的号码REAL二进制位,并没有0B盈呢?所以:
>>> X = 5
>>>斌(X)
0101
>>> Y = -5
>>>斌(Y)
1011
不知道如何得到你想要使用标准库的内容。有脚本和包的少数在那里,会做转换为你。
我只是想说明为什么,为什么它不是跛。
斌()不返回二进制位。将其转换为二进制字符串的数目。领先的0B告诉你处理的二进制数,按Python语言定义的相互preTER。这种方式,您可以直接与二进制数的工作,像这样
>>> 0B01
1
>>> 0b10
2
>>> 0b11
3
>>> 0B01 + 0b10
3
这不是跛。这是伟大的。
<一个href=\"http://docs.python.org/library/functions.html#bin\">http://docs.python.org/library/functions.html#bin
斌(X)
转换的整数为二进制字符串。
块引用>
块引用><一个href=\"http://docs.python.org/reference/lexical_analysis.html#integers\">http://docs.python.org/reference/lexical_analysis.html#integers
整数和长整型常量由以下词法定义描述:
bininteger :: =0(b的|B)bindigit +
bindigit :: =0| 1
块引用>
块引用>Integers in Python are stored in two's complement, correct?
Although:
>>> x = 5 >>> bin(x) 0b101
And:
>>> x = -5 >>> bin(x) -0b101
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
解决方案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() 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)
Convert an integer number to a binary string.
http://docs.python.org/reference/lexical_analysis.html#integers
Integer and long integer literals are described by the following lexical definitions:
bininteger ::= "0" ("b" | "B") bindigit+
bindigit ::= "0" | "1"
这篇关于二进制补码在Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!