user573566 user573566 - 8 months ago 28
C Question

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

I know and understand the result.

For example 7 (decimal) = 00000111 (binary)

and 7 >> 2 = 00000001 (binary)

00000001 (binary) is same as 7 / 4 = 1

So 7 >> 2 = 7 / 4

But I'd like to know how this logic is created.

Can anyone elaborate on this logic ?

(Maybe it's just popped up in a genius head ?)

And is there any other similar logics like this ?


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. Here is for the starters.

This is my favorite book: on bit-twiddlery.