Vlad
Vlad

Reputation: 3181

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?

Upvotes: 4

Views: 142

Answers (3)

Ian
Ian

Reputation: 30813

>> 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)

Upvotes: 5

serv-inc
serv-inc

Reputation: 38267

This is actually a part of C and C++, called a Compound assignment operator.

tmp >>= 7

is equivalent to

tmp = tmp >> 7

with >> as the bitwise right shift.

Upvotes: 1

Nick Zuber
Nick Zuber

Reputation: 5637

>> 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

Upvotes: 2

Related Questions