How to get binary representation of negative numbers in python

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

This is not what I want. It just keeps the sign -and converts the number. I want the actual representation of negative numbers.

Is there any method in python that does this?

+4
source share
1 answer

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

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

UPDATE

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

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

All Articles