Lesson Contents

Bitwise operators are one of the operator types and can **compare binary numbers** and are mostly used in mathematical calculations. As a network engineer, it’s unlikely that you need to use these operators often. They might be useful when you want to calculate subnets or when you work on security-related scripts where you have to use cryptographic functions.

Since these operators work with binary numbers, it’s easier if we can see binary numbers instead of decimal numbers. Fortunately, Python has the format function which allows us to format a decimal number into binary. Let me show you a quick example where we translate decimal number 16 into a binary number:

The ’08b’ part tells Python to show 8 binary numbers, including leading zeroes. This makes it easier to look at binary numbers when you want to compare them.

Now let’s look at those bitwise operators.

## AND

The AND operator uses the & symbol and sets **each bit to 1 if both bits are 1. Otherwise, it sets the bit to 0**. Take a look at the following code:

Let me explain this:

- We print decimal numbers 8 and 9 in binary.
- We use the AND operator with decimal numbers 8 and 9 and store the result in variable “and_result”.
- We format variable “and_result” into binary and store the result in variable “binary_and_result”.
- We print variable “binary_and_result”.

## OR

The OR operator uses the | symbol and **returns a 1 if either of the bits is 1, otherwise, it returns a 0**. Here is an example:

## XOR

The XOR operator uses the ^ symbol and **returns a 1 when one bit is 1 and the other is 0. Otherwise, it returns a 0**. It looks like this:

Only the 8th bit has a 1 and 0, so it becomes a 1. The first 7 bits are all set to 0.

## NOT

The NOT operator uses the ~ symbol and inverts all the bits. **Bits that are 0 become 1, and bits that are 1 become 0**. Let’s have a look:

This output might look strange, a negative binary value. It looks like this because Python uses signed number representation.

## Shift Operators

Shift operators shift the bits left or right. The result is the same as if you would multiply or divide a number by two.

### Shift Left

Let’s shift some bits to the left with the << symbol:

### Shift Right

We can also shift bits to the right with the >> symbol:

## Conclusion

You learned how to compare binary values with the Python bitwise operators:

- AND: Sets each bit to 1 if both bits are 1. Otherwise, it sets the bit to 0.
- OR: Sets each bit to 1 if either of the bits is 1. Otherwise, it returns a 0.
- XOR: Sets each bit to 1 when one bit is 1 and the other bit is 0. Otherwise, it returns a 0.
- NOT: Inverts all bits.
- Shift operators shift the bits to the left or to the right.

I hope you enjoyed this lesson. If you have any questions, please leave a comment.