2016-01-06 92 views
3

我有這樣的代碼:X >> = N是做什麼的?

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

但我不明白怎麼tmp >>= 7作品?

+2

看起來像一個位移運算符給我。 tmp被重新分配給移位操作的結果。看到這個問題http://stackoverflow.com/questions/460562/understand-the-shift-operator – Alex

+1

移位運算符 –

+0

另請參見:http://stackoverflow.com/questions/25495042/what-is-the-operator- in-c/25495211#25495211 –

回答

5

>>被稱爲右按位移運營商。而且,由於存在和>>附加=後(形成複合賦值操作者>>=),因此分配分配器變量(tmp)將共享

或者換句話說,利用給定的例子,

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

相當於

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

現在談談按位移操作,我認爲這是最好的說明它使用一個例子。

假設的tmp0xFF001111 1111 0000 0000在二進制表示),那麼如果我們按比特層面看,中>>=操作是這樣的

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

因此,新的價值tmp會是0x01FE(即0000 0001 1111 1110

2

>>是位移位操作者

tmp >>= 7正在轉移tmp 7位到右側,其設置到該值。

循環將繼續下去,直到tmp

+0

是的,我知道什麼是位移,但這是我第一次看到它被重新分配。謝謝! – Vlad

+0

@Vlad認爲它僅僅是一個'+ ='而不是加法,它有位移 –

相關問題