21

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?

3
  • Which one is the actual representation? Commented Feb 7, 2015 at 14:59
  • 1
    Do you mean two's complement? To how many bits? Commented Feb 7, 2015 at 15:00
  • 1
    @jonrsharpe Yeah two complement representation. Upto, standard 32 bit. Commented Feb 7, 2015 at 15:01

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

3 Comments

And even >>> bin((1 << 64) - 1) '0b1111111111111111111111111111111111111111111111111111111111111111'
For bonus points, you can cover positive and negative in one go with bitwise and: bin(((1 << 32) - 1) & -5)
@cobbal, Thank you for your comment. I updated the answer according to you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.