Thor Correia Thor Correia - 2 years ago 122
Python Question

Two's Complement Binary in Python?

Integers in Python are stored in two's complement, correct?


>>> x = 5
>>> bin(x)


>>> x = -5
>>> bin(x)

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)
>>> y = -5
>>> bin(y)

Answer Source

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
>>> 0b10
>>> 0b11
>>> 0b01 + 0b10

that's not lame. that's great.


Convert an integer number to a binary string.

Integer and long integer literals are described by the following lexical definitions:

bininteger ::= "0" ("b" | "B") bindigit+

bindigit ::= "0" | "1"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download