20

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?

Bhavesh Munot
  • 675
  • 1
  • 6
  • 13

1 Answers1

26

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'
falsetru
  • 357,413
  • 63
  • 732
  • 636