user573566 - 1 year ago 46

C Question

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 ?

Answer Source

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.