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:

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.

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

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

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.


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

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Join our mailing list

Join our mailing list to receive awesome articles about learning Python and Computer Science in a fun and accessible way, straight to your inbox.

 Take your Python skills to the next level!

with our free email course on object oriented programming with Python