Bit Manipulation made simple

Bitwise Operation

Bit manipulation (or bitwise operation) are used in Data compression (data is compressed by converting it from one representation to another, to reduce the space), Exclusive-Or Encryption (an algorithm to encrypt the data for safety issues). In order to encode, decode or compress files, we have to extract the data at bit level. Bitwise Operations are faster and closer to the system (which runs in bits 'zero & one'.) and sometimes optimize the program to a good level at bit level programming.

The knowledge of binary numbers in mathematics is required to understand bitwise operations.

Binary numeration is very simple to understand, it is very similar to the basic mathematics operation.

Normal number is in base 10,

Example: 256 = 10²x2 + 10¹x5 + 10⁰x6

In binary number (base 2);

1101 = 2³x1 + 2²x1 + 2¹x0 + 2⁰x1

Bitwise operators : compare data for various operations.

  1. AND (&) : for AND if both are true (one(1)), the result is true (one(1))

Example:

Int y = 6; //6 = 00000110

Int x = 12; //12 = 00001100

Z = y & x; //z = 00000100

2) OR(|) : for OR if at least one is true (one(1)), the result is true (one(1))

Example:

Int y = 6; //6 = 00000110

Int x = 12; //12 = 00001100

Z = y & x; //z = 00001110

3) XOR(^) : for XOR only one of the bit needs to be one(1) to assign 1, if both are one(1) then, we assign it to be zero (0).

Example:

Int y = 6; //6 = 00000110

Int x = 12; //12 = 00001100

Z = y & x; //z = 00001010

4) left shift (<<) : we shift the bit to a step left.

Example: to left shift y by 1 step;

y=6; //6 = 00000110

y << 1; that is = 00000110

Answer is now = 00000011

Which is 3 in base10

5) right shift (<<) : we shift the bit to a step right.

Example: to right shift y by 1 step;

y=6; //6 = 00000110

y >> 1; that is = 00000110

Answer is now= 00001100

Which is 12 in base10.

Hope it helps your understanding. Thank you.