Wednesday, November 13, 2013

bitwise poerators << and >>

Bit is a digit of a binary representation of a number. In C++ there are operators referring to bits.
 One of those operators are the operators >> and <<. If we try to translate the operator << into english we would get this definition move the current bits to the right. And the >> stands for move the bits to the left. The operator is mostly used for multiplying the number with the power of 2.  Now we will use an example to make it clear. 

Image somewhere in our memory we have the decimal number 3 which is 11 in binary.

1 2 3 4 5 6 7 8
0 0 0 0 0 1 1 0
The start point is the position 6 and the endpoint is 7.  Now if apply 3<<2 (means move 2 bits to the left)
we will get this
1 2 3 4 5 6 7 8
0 0 0 1 1 0 0 0
NOTE that the endpoint is going to stay the same . Its 7 but the start point moved to position 4. We sure know that binary 1100 is 12 which is 3*4.
So    n<<m=n*2^m


and   n>>m=n/2^m

No comments:

Post a Comment