Bitwise operation - Zero-fill right shift (>>>) usages?

后端 未结 2 1700
生来不讨喜
生来不讨喜 2021-01-02 10:12

Generally speaking, bit shifting (>> , <<) allows us to divide / multiply by ^2

Example :

      9 (base 10): 0         


        
2条回答
  •  走了就别回头了
    2021-01-02 11:02

    Let's say you were programming something to mimic a piece of hardware, specifically a shift register.

    To make things easier I'll use 8 bits instead of 32 bits as in your question.

    We can add 128 every time we want to feed a high bit into this shift-register, since it will make the leftmost bit 1.

    // Assume n is initialised to 0, so n = 00000000 in binary
    n += 128;                    // now n = 10000000 in binary
    

    If we shift using >>> every time you want to simulate a clock cycle, then after 8 "clock cycles" we will have that 1 at the rightmost bit. If we read that rightmost bit out then we will get a delayed version of what was fed into the leftmost bit 8 cycles ago.


    This is only one example where the bits are not interpreted as a number, and I am sure there are many more. I think you'll find a few more uses elsewhere, especially in software meant to mimic hardware circuits/building blocks.

提交回复
热议问题