Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What X >>= N does?

I have this code:

tmp = (uint)len;
writer.CurPosition = value + 1;
do
{
    value++;
    writer.dest.WriteByte((byte)((tmp & 0x7F) | 0x80));
} while ((tmp >>= 7) != 0);

But I don't understand how tmp >>= 7 works?

like image 204
Vlad Avatar asked Sep 13 '25 17:09

Vlad


2 Answers

>> is called right bitwise-shift operator. And since there is and additional = after >> (forming a compound assignment operator >>=), thus the assigned and the assigner variable (tmp) will be shared.

Or in other words, using the given example,

tmp >>= 7; //actually you use tmp both to assign and to be assigned

is equivalent to

tmp = tmp >> 7; //actually you use tmp both to assign and to be assigned

Now about the bitwise-shift operation, I think it is best to illustrate it by using an example.

Suppose the value of tmp is 0xFF00 (1111 1111 0000 0000 in binary representation), then if we see in the bitwise level, the operation of >>= would look like this

1111 1111 0000 0000 //old tmp
------------------- >> 7
0000 0001 1111 1110 //Shifted by 7 -> this is going to be the new value for tmp

Thus, the new value for tmp would be 0x01FE (that is 0000 0001 1111 1110)

like image 177
Ian Avatar answered Sep 16 '25 06:09

Ian


>> is a bit shift operator

tmp >>= 7 is shifting tmp 7 bits to the right and setting it to that value.

The loop will continue until tmp is zero

like image 27
Nick Zuber Avatar answered Sep 16 '25 07:09

Nick Zuber