# Python Bitwise Operators

Bitwise operators and bit manipulation are like recursion in that they are both topics that are fundamental to computing, yet the amount of use you will make of them will vary gratly depending on your domain. Bit manipulation is certainly important for job interviews at companies like the “bigN” (Google, FB, etc.) and other places where a deep knowledge of fundamentals is expected and required. It is also an very important when working with embedded systems, and some other areas as shown below.

## Applications of Bitwise Operators in Computing

• Job interviews and ongoing work for Big Tech
• Embedded systems programming
• Encryption and compression algorithms
• Cultural awareness in the tech age
• Low-level programming
• Working with graphics
• Device drivers for mainstream operating systems
• Communications protocol packet assembly

Knowledge of bitwise operators is also important from the perspective of cultural education in the information age. Technology that uses these processes surrounds us in our everyday lives, and it makes sense to have some understanding of the human knowledge that underpins their existence.

Some of the most commonly used bitwise operators are:

• & (bitwise AND)
• | (bitwise OR)
• ~ (bitwise NOT)
• ^ (bitwise XOR)
• << (bitwise left shift)
• >> (bitwise right shift)

You can play around with these operators in a Python shell, which a great way to get a quick sense of how some piece of Python functionality works or make a quick check that it behaves as expected.

For example:

``````>>> 16 >> 1  # Divide by 2
8
>>> 12 << 2  # Multiply by 4
48
>>> 11 & 1   # A trick to check for even/odd
1
>>>
``````

These operators will make much more sense if you look at the binary representation of the operands. I’ve provided some code below that you might find helpful in your exploration. Bear in mind the formatting I have used will only work for positive values.

``````# A couple of useful functions
print(int('00100001', 2))  # Convert binary number in string form to decimal int
print(bin(20))  # String representation of binary number

# Python Bitwise Operator Examples
# NB the output is designed to work for positive values only!

a = 24
b = 9

c = a & b  # Bitwise AND
print(f"{a} & {b} = {c}")
print()
print(f"  {bin(a)[2:].zfill(8)}")
print(f"& {bin(b)[2:].zfill(8)}")
print("----------")
print(f"= {bin(c)[2:].zfill(8)}")
print()

c = a | b  # Bitwise OR
print(f"{a} | {b} = {c}")
print()
print(f"  {bin(a)[2:].zfill(8)}")
print(f"| {bin(b)[2:].zfill(8)}")
print("----------")
print(f"= {bin(c)[2:].zfill(8)}")
print()

c = a ^ b  # Bitwise XOR
print(f"{a} ^ {b} = {c}")
print()
print(f"  {bin(a)[2:].zfill(8)}")
print(f"^ {bin(b)[2:].zfill(8)}")
print("----------")
print(f"= {bin(c)[2:].zfill(8)}")
print()

b = 2
c = a >> b  # Right-shift by 2. I.e a // 4
print(f"{a} >> {b} = {c}")
print()
print(f"      {bin(a)[2:].zfill(8)}")
print(f">> {b}  {bin(b)[2:].zfill(8)}")
print("--------------")
print(f"=     {bin(c)[2:].zfill(8)}")
print()

b = 2
c = a << b  # Left-shift by 2. I.e a * 4
print(f"{a} << {b} = {c}")
print()
print(f"      {bin(a)[2:].zfill(8)}")
print(f"<< {b}  {bin(b)[2:].zfill(8)}")
print("--------------")
print(f"=     {bin(c)[2:].zfill(8)}")
print()
``````

The main part of the code will give the following output:

``````24 & 9 = 8

00011000
& 00001001
----------
= 00001000

24 | 9 = 25

00011000
| 00001001
----------
= 00011001

24 ^ 9 = 17

00011000
^ 00001001
----------
= 00010001

24 >> 2 = 6

00011000
>> 2  00000010
--------------
=     00000110

24 << 2 = 96

00011000
<< 2  00000010
--------------
=     01100000
``````

You can of course change the values of `a` and `b` to perform different calculations.

## Recommended Books on Algorithms and Data Structures

Please note as an Amazon Affiliate I earn from qualifying purchases.

## A Python Program using Bitwise Operators

The following program uses Python bitwise operators to collect the powers of `2` that can be used to represent a decimal number provided as an arguments. See if you can understand how it works, particularly the `&` and `<<` bitwise operators. Add print statements to output intermediate values if it helps you to see what is happening at a particular step.

``````def binary_decomp(n):
powers = []
i = 1
while i <= n:
if i & n:
powers.append(i)
i <<= 1
return powers

print(binary_decomp(10))
print(binary_decomp(32))
print(binary_decomp(127))
print(binary_decomp(-24))
print(binary_decomp(0))
``````

Output:

``````[2, 8]
[32]
[1, 2, 4, 8, 16, 32, 64]
[]
[]
>>>
``````

Now you know about bitwise operators is Python. I hope this knowledge serves you well. Happy computing!

Sharing is caring!