Custom Search

PYTHON: Bitwise Operators

In computer programming, a bitwise operation operates on a 'bit string', a bit array or a binary numeral at the level of its individual bits. It is directly supported by the processor making it, in general, a faster way of computing a value and uses less power than other operations.

Most bitwise operations are presented as two-operand instructions where the result replaces one of the input operands.

You can find out about binary numbers by looking at this page.

AND Sets each bit to 1 if both bits are 1

If you enter the code:

6&3

The computer will return an answer of 2

6 = 110

3 = 011

so the result will be 010 which is 2

| OR Sets each bit to 1 if one of two bits is 1

If you enter the code:

6|3

The computer will return an answer of 7

6 = 110

3 = 011

so the result will be 111 which is 7

 

 ^ XOR Sets each bit to 1 if only one of two bits is 1

If you enter the code:

6^3

The computer will return an answer of 5

6 = 110

3 = 011

so the result will be 101 which is 5

NOT

Inverts all the bits - including the bit that represents the +/- representation. So 0 becomes 1 and 1 becomes 0.

This is semantically the same as calculating ~x == -x-1.

For example, the bitwise NOT expression ~0 becomes -1, ~9 becomes -10, and ~32 becomes -33.

If you enter the code:

~6

The computer will return an answer of -7

<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off

The Bitwise left shift operator is used for multiplying a number by powers of 2. The bitwise left shift operator in Python shifts the bits of the binary representation of the input number to the left side by a specified number of places. The empty bits created by shifting the bits are filled by 0s.

Let's find out what left shifting 14 by 2 would result in...

00001110 is number 14

If we left shift it two bit places we get 00111000 which is decimal number 56

(25 + 24 + 23 = 32 + 16 + 8 = 56)

>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

The bitwise right shift operator in python is used to divide a number by powers of 2. After shifting, the rightmost bits whether they are 1 or 0 will be discarded, and the empty leftmost bits will be filled with 0s.

Let's find out what right shifting 14 by 2 would result in...

00001110 is number 14

If we right shift it two bit places we get 00000011 which is decimal number 3.