Programming machines has always been a difficult task; newer techniques try to solve this by automating the tougher tasks, the low-level handling of the machines. However, some gates have been left open to the older methods, so whenever you wish to use them you are able to do so. At least this applies to C/C++. In this article you'll see how to use bitwise operators in C/C++, and learn why you may want to use them.

Bitwise Operators - Shift Operators (Page 2 of 5 )

These two (<< and >>) are called shift operators in terms of programming. There is one for the left direction (<<) and one for the right direction (>>), respectively. They require two integer values according to the following template:

[What to shift][The direction] [With how many bits]

For example:

Operation / /-> Effect in the memory

unsigned char a = 1; // -> 00000001

a << 3; // -> 00001000

a >> 3; // -> 00000000

From the upper example you may have already figured out that for the left shift operation, the entire byte is shifted by 1 and from the right comes a 0. As for the right shift, the situation is a little more complex. In the case of an unsigned type (like in the case above), it only leaves the number of bits that we shift, and from left the comes a 0 for each one of them. However when we have signed types the incoming shift at the left side is 1. So for the example above the same shifting would result in: 11100000.

Now if we put these operators together and the knowledge of transforming from the binary system to decimal, we could observe that moving with a bit means nothing more and nothing less than an action of dividing or multiplying by two. And here is why:

a * 2 = a << 1

a / 2 = a >> 1

So raising to the second power can be reduced to a trivial bit shifting along these lines:

2 ^ 4 = 1 << 4

We must also mention that the implementation of the right shift operator is device- and compilation- dependent, and is the main reason why using it isn't a recommended in all cases. This is because the sign operator is implemented differently here and there. For example, -1 can be represented both as 10000001 and 11111111. In the first case it is signaled by the first sign bit if the integer is negative (sign bit) or not, while in the second, -1 is defined as the largest number's complement.