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

后端 未结 10 1463
谎友^
谎友^ 2020-12-05 09:25

I know and understand the result.

For example:


7 (decimal) = 00000111 (binary)
and 7 >> 2 = 00000001 (binary)
10条回答
  •  隐瞒了意图╮
    2020-12-05 09:42

    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.

提交回复
热议问题