Saturday, February 9, 2019

Bitwise Operators

Bitwise operators are used to logical operations on each bit in binary form of a number. The operation takes place bit by bit of the number.

+-------+------------------+
|   &   |   Bitwise and    |
|   |   |   Bitwise  or    |
|   ^   |   Bitwise  xor   |
|   ~   |   Bitwise not    |
+-------+------------------+

To understand this lets take two numbers, a = 58 and b = 30. The binary representation of a and b is,

a = 00111010
b = 00011110

Now let us perform bitwise operations on these numbers. The table below lists the results of the operations.

+------------+-----------+---------------+
|  Examples  |  Results  | Decimal Value |
+------------+-----------+---------------+
|    a & b   |  00011010 |      26       |
|    a | b   |  00111110 |      62       |
|    a ^ b   |  00100100 |      36       |
|     ~a     | -00111011 |     -59       |
|     ~b     | -00011111 |     -31       |
+------------+-----------+---------------+

.

No comments: