Bitwise Operators in python



Introduction

Bitwise operators work on bits and perform the bit-by-bit operation. Hence it is called a bitwise operator. Therefore, all the integer values will be converted to binary digits which are 0s and 1s for bitwise calculation.

So, how to convert an integer to a binary number and vice versa?

Well, it is easy to convert the integer to binary number in python. Python’s built-in function bin() can be used to obtain a binary representation of an integer number. For instance, we know that binary representations for integer value 10 are 1010. So, how to check in a python interpreter?

>>> bin(10)
'0b1010'  # b is to represent that it is a binary digit

Now to convert binary to an integer, you have to use the built-in int() function. The syntax is >>>int(‘binary number’, 2); here 2 is a base number, where binary takes base 2 to convert into a number system.

For example, we have seen that binary number 1010 represents integer value 10. So, let’s check in python interpreter;

>>> int("1010",2)
10

Now, let’s look into six ways in which python supports bitwise operators:

Five bitwise operators
1. Binary AND (&)

Sets each bit to 1 if both bits are 1. Otherwise, it will be 0.

Example:

>>> a = 10
>>> b = 11
>>> a & b
10

An explanation for the above example:

Bitwise AND operator

2. Binary OR (|)

Sets each bit to 1 if one of two bits is 1. Otherwise, to 0.

Example:

>>> a = 10
>>> b = 11
>>> a | b
11

An explanation for the above example:

3. Binary XOR (^)

Sets each bit to 1 if the corresponding bits of two operands are opposite. Otherwise to 0.

Example:

>>> a = 10
>>> b = 11
>>> a ^ b
1

An explanation for the above example:

4. Binary NOT (~)

Returns 1’s compliments of the number.

Example 1:

>>> a = 10
>>> ~ a
-11

An explanation for example 1:

Example 2:

>>> b = 11
>>> ~b
-12

An explanation for example 2:

5. Binary left shift (<<)

Left shift operators shift all bits towards the left by a certain number of specified bits.

Example:

>>> a = 10
>>> a << 1
20

Explanation: binary number for integer value 10 is 1010. So, when we left-shift the value by 1, it becomes 10100 which is the same as 00010100. Therefore, the decimal value for 00010100 is 20.

>>> int("00010100",2)
20
6. Binary right shift (>>)

Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off as per the specified bits.

Example:

>>> a = 10
>>> b = 11
>>> a >> 1
5
>>> b >> 1
5

Explanation: Binary value for decimal number 10 is 1010. When we apply a right shift by 1; the rightmost bit falls off and it becomes 0101 which is 5 in decimal number.

>>> int("0101",2)
5
Other operators used are: