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 7,713 times
6

GiveItAwayNow
- 417
- 1
- 4
- 15
-
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
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))

Ali Nikneshan
- 3,500
- 27
- 39
-
1
-
-
'<' is missing in the 2nd code! be careful while posting answers – Nikhila Munipalli Feb 29 '20 at 08:11
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.

Błażej Michalik
- 4,474
- 40
- 55

R Nar
- 5,465
- 1
- 16
- 32