Negative numbers to binary system with Python
Question:
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.
Answers:
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))
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.
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.
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))
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.