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.
Asked
Active
Viewed 6,326 times
4
GiveItAwayNow
- 377
- 3
- 14
-
Python has arbitrary precision integers, so your expectation of twos-complement arithmetic is incorrect. Perhaps pack or struct can help you out. – President James K. Polk Dec 15 '15 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. – Ignacio Vazquez-Abrams Dec 15 '15 at 22:11
2 Answers
8
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))
Ali Nikneshan
- 3,347
- 25
- 37
2
Use %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.
R Nar
- 5,315
- 1
- 15
- 30