6

I'm solving a task using Python. I need to count the number of non-zero bits in a given value. I don't have any problems with positive numbers as I use the function bin() and count the number of '1', but can't understand what's wrong with negative. In example, -1 is equal to 11111111111111111111111111111111, but when I use the function bin() it gives '-0b1'. Please, tell me how can I convert it right.

2
  • Python has arbitrary precision integers, so your expectation of twos-complement arithmetic is incorrect. Perhaps pack or struct can help you out. Commented Dec 15, 2015 at 22:11
  • "In example, -1 is equal to ..." Incorrect. It is equal to 0b11...11. But since there's no way to represent an infinite number of bits, we just use -0b1 instead. Commented Dec 15, 2015 at 22:11

2 Answers 2

11

Just need to add 2**32 (or 1 << 32) to the negative value.

bin(-1+(1<<32))
'0b11111111111111111111111111111111'

or use following command for all the values:

a = bin(val if val>0 else val+(1<<32))
Sign up to request clarification or add additional context in comments.

3 Comments

Or, in general, 2**k to simulate a k-bit "word" size.
remember to mark answer if answer is helpful and satisfying
'<' is missing in the 2nd code! be careful while posting answers
2

Use num % maxnum:

bin(-1 % 20) == bin(19)

The reason you are getting what you have, as explained in the comments, is because of how ints are represented in binary. I would not be able to tell you much, but it has to do with a variety of things including arbitrary byte size, unsigned/signed ints, etc etc.

So to achieve what you want (the int to wrap around some arbitrary max value, in this case 32 bit), just use modulo:

bin(num % 2*32)

Just a note that the difference between using % versus simply + the max num is that this will work for both positive and negative numbers.

1 Comment

Should it be 2 ** 32 instead of 2 * 32?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.