# Binary Logic and Bitwise Operators in Python

I’m working my way through “Python Programming For Beginners” from AMZ Publishing. Regarding bitwise operators, can someone please explain to me if x = 5, how does one get -6 from ~x? Thank you for your help.

If you have an 8-bit number than flipping all bits of x = 5 gives

``````1111 1010
``````

This can be interpreted either as a large positive or as a small negative number (using 2-complement representation, see links): as 250 or as -6.

Python integers don’t have fixed length, so you can think of 5 as `0000 ... 0101` and -6 as `1111... 1010`
(infinite binary expansions), but the method is basically the same as for N-bit numbers. But if you have infinite expansions, then the bit-flipped number can only be interpreted as a negative number since there is no specific positive number corresponding to `1111...1111`.

1 Like

Here’s a recent thread on the same topic: Bitwise Operator Negation

1 Like

For `1111 1010`, how did you get 122? I get 250!

Ha - I forgot one one… 1111010 = 122. Of course it should be 250. Fortunately no NASA launch depended on this. I corrected the earlier mail.

Just remember:

bit 7 2^7 = 128
bit 6 2^6 = 64
bit 5 2^5 = 32
bit 4 2^4 = 16
bit 3 2^3 = 8
bit 2 2^2 = 4
bit 1 2^1 = 2
bit 0 2^0 = 1

Wherever there is a ‘1’, multiply it by the value on the column with the
2^n results. ‘~’, means that you are negating the values.

0 → 1
0 → 1
0 → 1
0 → 1 implies negative sign
0 → 1 … 4
1 → 0
0 → 1 … 2
1 → 0

-6

So, if you have x = 5, then ~x = -6 (give it a try)

Note that this is known in boolean logic arithmetic as the NOT function. Not to be confused with the
negative two’s complement for the representation of a negative number.

If you’re also looking on how to convert negative binary numbers (and by extension HEX numbers since all you have to do is group them into groups of four), you can use the numpy module. Here is a discussion on the topic:
[numpy.binary_repr — NumPy v1.26 Manual]

https://numpy.org/doc/stable/reference/generated/numpy.binary_repr.html

Ex.

``````import numpy as np

np.binary_repr(-9, 8)
>> '11110111'
``````

The first number entered is the number that you want converted and the second number is how many
bits that you want in your answer. The number of bits should be the minimum you need to hold that number in binary format but should be in groups of four.

You also have to remember that in Python `^` is bitwise exclusive OR and `**` is the exponentiation (power) operator.