How to get binary representation of negative numbers in python

Bhavesh Munot picture Bhavesh Munot · Feb 7, 2015 · Viewed 10.7k times · Source

When I enter bin(-3) it just shows -0b11.

Which is not what I want. It just keeps that - sign and convert the number. I want the actual representation of negative numbers.

Is there any method in python which does that?

Answer

falsetru picture falsetru · Feb 7, 2015

Depending on how many binary digit you want, subtract from a number (2n):

>>> bin((1 << 8) - 1)
'0b11111111'
>>> bin((1 << 16) - 1)
'0b1111111111111111'
>>> bin((1 << 32) - 1)
'0b11111111111111111111111111111111'

UPDATE

Using following expression, you can cover both positive and negative case:

>>> bin(((1 << 32) - 1) & -5)
'0b11111111111111111111111111111011'