Can anyone explain why '>>2' shift means 'divided by 4' in C codes?

I think you are confused by the "2" in:

7 >> 2

and are thinking it should divide by 2.

The "2" here means shift the number ("7" in this case) "2" bit positions to the right.

Shifting a number "1"bit position to the right will have the effect of dividing by 2:

8 >> 1 = 4    // In binary: (00001000) >> 1 = (00000100)

and shifting a number "2"bit positions to the right will have the effect of dividing by 4:

8 >> 2 = 2    // In binary: (00001000) >> 2 = (00000010)

Elaborating on Aniket Inge's answer:

Number: 30710 = 1001100112

How multiply by 10 works in decimal system

10 * (30710)

= 10 * (3*102 + 7*100)

= 3*102+1 + 7*100+1

= 3*103 + 7*101

= 307010

= 30710 << 1

Similarly multiply by 2 in binary,

2 * (1001100112)

= 2 * (1*28 + 1*25 + 1*24 + 1*21 1*20)

= 1*28+1 + 1*25+1 + 1*24+1 + 1*21+1 1*20+1

= 1*29 + 1*26 + 1*25 + 1*22 + 1*21

= 10011001102

= 1001100112 << 1


It didn't "pop-up" in a genius' head. Right shifting binary numbers would divide a number by 2 and left shifting the numbers would multiply it by 2. This is because 10 is 2 in binary. Multiplying a number by 10(be it binary or decimal or hexadecimal) appends a 0 to the number(which is effectively left shifting). Similarly, dividing by 10(or 2) removes a binary digit from the number(effectively right shifting). This is how the logic really works.

There are plenty of such bit-twiddlery(a word I invented a minute ago) in computer world.

http://graphics.stanford.edu/~seander/bithacks.html Here is for the starters.

This is my favorite book: http://www.amazon.com/Hackers-Delight-Edition-Henry-Warren/dp/0321842685/ref=dp_ob_image_bk on bit-twiddlery.


It is actually defined that way in the C standard.

From section 6.5.7:

The result of E1 >> E2 is E1 right-shifted E2 bit positions. [...] the value of the result is the integral part of the quotient of E1 / 2E2

On most architectures, x >> 2 is only equal to x / 4 for non-negative numbers. For negative numbers, it usually rounds the opposite direction.

Compilers have always been able to optimize x / 4 into x >> 2. This technique is called "strength reduction", and even the oldest compilers can do this. So there is no benefit to writing x / 4 as x >> 2.

Tags:

C

Divide

Shift