Understanding Bitwise Operators in Python

There are 6 binary/bitwise operators in Python:

  • Complement/Not (~)
  • And (&)
  • Or (|)
  • XOR (^)
  • Left Shift (<<)
  • Right Shift (>>)

A fantastic python method to help us along our journey is bin(). The bin function will return a binary representation of a base 10 integer we pass to it.

>>> bin(1) '0b1' >>> bin(5) '0b101'
Code language: Python (python)

Now let’s explore the 6 bitwise operators by learning a bit about each of them.

Complement/Not (~)

Returns one’s complement of the number.

It is unary and has the effect of ‘flipping’ bits.

Returns the complement of x – the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x – 1.

And (&)

Returns 1 if both the bits are 1 else 0.

Operator copies a bit to the result if it exists in both operands

Does a “bitwise and”. Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it’s 0.

In fact, we can also use the bitwise & to tell us if an integer is odd or even:

>>> 2 & True 0 >>> 3 & True 1 >>> 11 & True 1 >>> 9 & True 1 >>> 8 & True 0 >>> 80 & True 0 >>> 82 & True 0 >>> 83 & True 1
Code language: Python (python)

Or (|)

Returns 1 if either of the bit is 1 else 0.

It copies a bit if it exists in either operand.

Does a “bitwise or”. Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it’s 1.

XOR (^)

Returns 1 if one of the bit is 1 and other is 0 else returns false.

It copies the bit if it is set in one operand but not both.

Does a “bitwise exclusive or”. Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it’s the complement of the bit in x if that bit in y is 1.

Shifting

These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two.

Left Shift (<<)

Shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two.

The left operands value is moved left by the number of bits specified by the right operand.

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

Right Shift (>>)

Shifts the bits of the number to the right and fills 0 on voids left as a result. Similar effect as of dividing the number with some power of two.

The left operands value is moved right by the number of bits specified by the right operand.

Returns x with the bits shifted to the right by y places. This is the same as //’ing x by 2**y.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments