Bitwise operators

train

To perform bit-level operations in C/C++/Python/C#, bitwise operators are used.

Bitwise OR (|)

The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. Let's see the binary representation of this operation:


10 = 00001010 (in binary)
15 = 00001111 (in binary)

Bitwise OR operation of 10 and 15

    00001010
  | 00001111
    ________
    00001111 = 15 (in decimal)
    

  Console.WriteLine(10|15); // Output is 15

Bitwise AND (&)

The output of bitwise AND is 1 if both corresponding bit of two operands is 1 otherwise it returns 0. Let's see the binary representation of this operation:


10 = 00001010 (in binary)
15 = 00001111 (in binary)

Bitwise OR operation of 10 and 15

    00001010
  & 00001111
    ________
    00001010 = 10 (in decimal)
    

  Console.WriteLine(10|15); // Output is 10

Bitwise XOR (^)

The result of the bitwise XOR operator is 1 if both corresponding bits of two operands are different.

10 = 00001010 (in binary)
15 = 00001111 (in binary)

Bitwise XOR operation of 10 and 15

    00001010
  ^ 00001111
    ________
    00000101 = 5 (in decimal)
    

  Console.WriteLine(10^15); // Output is 5

Bitwise NOT (~)

Bitwise Not or Complement operator is a unary operator, it works only on one operand. The operator means the negation of each bit of an input value. In other words, it changes from 1 to 0 and from 0 to 1.


10 = 00001010 (in binary)

Bitwise complement operation of 10

  ~ 00001010
    ________
    11110101 = 245 (in decimal)
    

Bitwise operators truth table


| A | B | A|B | A&B | A^B | ~A |
|---|---|-----|-----|-----|----|
| 0 | 0 |  0  |  0  |  0  | 1  |
| 1 | 0 |  1  |  0  |  1  | 0  |
| 0 | 1 |  1  |  0  |  1  | 1  |
| 1 | 1 |  1  |  1  |  0  | 0  |

Shift operators in C-family and Python

Binary shift operators shift all bits of the input value to the left or right based on the shift operator.

  • Right shift operator
  • Left shift operator

Right Shift operator (>>)

The right shift operator shifts all the bits to the right on specified bits. For instance, a = b >> 2, assigns a the result of shifting b to the right by two bits.


100 = 01100100 (in binary)

100 >> 1 = 00110010 // right shift by one bit, which is equivalent to a division by two
Console.WriteLine(100>>1); // Output is 50

100 >> 2 = 00011001 // right shift by two bits, which is equivalent to a division by four
Console.WriteLine(100>>2); // Output is 25

Left Shift operator (<<)

The left shift operator shifts all the bits to the left on specified bits.


50 = 00110010 (in binary)

50 << 1 = 01100100 // left shift by one bit, which is equivalent to a multiplication by two
Console.WriteLine(50<<1); // Output is 100

50 << 2 = 11001000 // left shift by two bits, which is equivalent to a multiplication by four
Console.WriteLine(50<<2); // Output is 200