Thor Correia Thor Correia - 7 months ago 17
Python Question

Two's Complement Binary in Python?

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

Answer

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"

Comments