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

后端 未结 10 1498
谎友^
谎友^ 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:44

    You can call it an idea of a genius mind or just the need of the computer language.

    To my belief, a Computer as a device never divides or multiplies numbers, rather it only has a logic of adding or simply shifting the bits from here to there. You can make an algorithm work by telling your computer to multiply, subtract them up, but when the logic reaches for actual processing, your results will be either an outcome of shifting of bits or just adding of bits.

    You can simply think that for getting the result of a number being divided by 4, the computer actually right shifts the bits to two places, and gives the result:

    7 in 8-bit binary = 00000111
    Shift Right 2 places = 00000001 // (Which is for sure equal to Decimal 1)
    
    Further examples:
    //-- We can divide 9 by four by Right Shifting 2 places
    9 in 8-bit binary = 00001001
    Shift right 2 places: 00000010 // (Which is equal to 9/4 or Decimal 2)
    

    A person with deep knowledge of assembly language programming can explain it with more examples. If you want to know the actual sense behind all this, I guess you need to study bit level arithmetic and assembly language of computer.

提交回复
热议问题