# Python Bitwise Operators

Introduce Python's binary function and bitwise operator AND, NOT and XOR. We use 0bxx to represent a binary, such as 1 = 0b1, 2 = 0b10, etc

**Related course:** Complete Python Programming Course & Exercises

## Convert to binary

Introduces the Python function `bin(x)`

, which is mainly used to find the binary value of the decimal number x

For example

```
bin(2) # is 0b10
```

Exercise: Print out the binary value of a number between 2 and 5

```
print bin(1)
for i in range(2,6):
print bin(i)
```

### Section III

Introduces the `int()`

function for Python

The most common use of the `int()`

function is that `int(str)`

is the conv. But int(str,base) can be used to convert a value in base to decimal, e.g. int("0b11",2) gives a value of 3

For example

```
>> print int("1",2)
>> print int("10",2)
>> print int("111",2)
>> print int("0b100",2)
>> print int(bin(5),2)
>> print int("11001001",2)
>> 01
```

## Bitwise Shift Operators

Introduces the left and right shift operations of Python

Examples of bit shift operations:

## Bitwise Left Shift Operator

The `<<`

operator shifts left.

```
Left Bit Shift (<<)
0b000001 << 2 = 0b000100 (1 << 2 = 4)
0b000101 << 3 = 0b101000 (5 << 3 = 40)
```

## Bitwise Right Shift operator

```
Right Bit Shift (>>)
0b0010100 >> 3 = 0b000010 (20 >> 3 = 2)
0b0000010 >> 2 = 0b000000 (2 >> 2 = 0)
```

3 Exercise: Shift the value of shift_right of the variable by two places and shift\left by two places.

```
shift_right = 0b1100
shift_left = 0b1
# Your code here!
shift_right >>= 2
shift_left <<= 2
print bin(shift_right)
print bin(shift_left)
```

## Bitwise AND operator

1 Introduces another type of Python bit algorithm &

2 for example A&B, that is, both bits are 1 for 1, otherwise 0

3 Exercise: Print out the results in binary 0b1110&0b101

```
print bin(0b1110&0b101)
```

### Bitwise NOT operator

1 An alternative bit operation for Python is introduced|

2 for example a|b, that is if there is 1 in both bits it is 1, otherwise it is 0

```
a: 00101010 42
b: 00001111 15
========================
a | b: 00101111 47
```

3 Exercise: Print out the results in binary 0b1110|0b101

```
print bin(0b1110|0b101)
```

## Bitwise XOR Operator

1 introduces an alternative bit operation for Python^

2 for example a^b, that is if the two bits are different then it is 1, otherwise it is 0

3 Exercise: print out the results in binary 0b1110^0b101

```
print bin(0b1110^0b101)
```

## Bitwise NOT operator

1 Introduces another kind of Python bit operation~

2 For example, the result of ~a is that the opposite of a is subtracted by one, which is satisfied for both positive and negative numbers of a

3 For example.

```
print ~-4 >> 3
print ~-3 >> 2
print ~-1 >> 0
print ~0 >> -1
print ~1 >> -2
print ~2 >> -2
print ~3 >> -2
```