Ad

Thursday, March 13, 2008

Right/Left Bit Shift Operators

This is the continuation of the article Operation on Bits and Bitwise Operators. If you haven’t read that, it is strongly recommended that you do, before proceeding with this article.

Bit shifting, as the name signifies, does shifting of bits in byte(s). There are basically two ways, in which bits (of a byte) can be shifted, either to the right, or to the left. Thus we have two types of bit shifting operator.

If you think logically, its pretty clear that for bit shifting in a byte, we need to have two data. We need the byte(s) to shift bits on and the number of bits to be shifted. Guess what, the two operators need these to data as operands!

Right Bit Shifting Operator (>>)

Syntax: res = var >> num;

This would shift all bits in the variable var, num places to the right which would get stored to the variable res. So for example if var has the following bit structure:

var = 00110101 (decimal 53)

And we do the following operation:

res = var >> 2;

We would get res as:

res = 00001101 (decimal 13)

As you can see, shifting of the bits to right disposes the bits (2) from the right and introduces 0s (2) to the left.

Left Bit Shift Operator (<<)

It is similar to the right shift operator except that the direction of shifting is opposite. The following is I think enough to explain this:

var = 00110101 (decimal 53)

And we do the following operation:

res = var << 2;

We would get res as:

res = 11010100 (decimal 212)

Just the opposite here, here bits get disposed from the left and new 0s are introduced to the right.

Related Articles:

No comments:

Post a Comment

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.