Search code examples
bit-manipulationbit-shiftcalculation

Is the bitwise `index>>=1` operation equal to the `index/2` and disregarding the remainder of the result?


So, I saw the following line index >>= 1 and I was wondering what did it mean. I did a little research and found out it was bitwise operations, but I had to simulate a few scenarios in my head and with bits that was impossible, because I had to convert everything and so on and so on, so I asked GPT about tips on how can I do it in my head. The trick I got from it was that >>=1 is equal to / 2 and disregarding the remainder. However, I figured that, for an example, if index = 4 and index = 5, then in both scenarios the result would be 2 which seemed odd to me.

So, I asked GPT about it and he said he did a mistake. Then I asked him which one is correct and he said the trick was correct, then said it was false and so on and so on. So, I researched online if it was true or not, yet I couldn't find it being mentioned.

So, I was wondering if anyone is more experienced and can confirm if the trick is real or was it another hallucination?


Solution

  • Yes, a right shift by 1 is the same as dividing by 2.

    • x >> 0 == x / 1
    • x >> 1 == x / 2
    • x >> 2 == x / 4
    • x >> 3 == x / 8

    etc.

    Consequently, doing left shifts can be used for multiplications of the same numbers:

    • x << 0 == x * 1
    • x << 1 == x * 2
    • x << 2 == x * 4
    • x << 3 == x * 8

    etc.

    This goes for positive integers and there are rules that must be followed. You are usually not allowed to rightshift equally many bits that the type carries or more. You are usually not allowed to leftshift so that the signbit gets set in signed integers. Some languages allows shifting negative numbers, some don't or leaves it implementation defined what happens if you do.