2016-06-15 36 views
2

我有一段我無法理解的c#代碼。在IntToBin循環的第一次迭代期間,我明白移位運算符將其轉換爲字節值7,但在第二遍中,字節值爲224. 224如何實現。整數轉換爲Bn

static void Main(string[] args) 
    { 
     IntToBin(2016,2); 
     //Console.Write((byte)2016); 
    } 

    public static byte[] IntToBin(int from, int len) 
    { 
     byte[] to = new byte[len]; 
     int max = len; 
     int t; 
     for (int i_move = max - 1, i_to = 0; i_move >= 0; i_move--, i_to++) 
     { 

      to[i_to] = (byte)(from >> (8 * i_move)); 
     } 

     return to; 
    } 

回答

1

據我所看到的,你有這條線

to[i_to] = (byte)(from >> (8 * i_move)); 

困難,你可以很容易地測試

2016 == 7 * 256 + 224 

現在,如何讓這些數字?

移位運算符>>是,事實上,一個整數除法通過兩個 權力:

>> 0 - no division (division by 1) 
    >> 1 - division by 2 
    >> 2 - division by 4 
    ... 
    >> 8 * i_move - dision by 2**(8*i_move) i.e. division by 256 ** i_move 

(byte)演員陣容,事實上,其餘操作% 256 因爲(byte)返回最後字節

現在,讓我們嘗試展開循環

i_move == 1 // max - 1 where max = 2 
    to[0] = (from/256) % 256; // = 7 

    i_move == 0 
    to[1] = (from/1) % 256; // = 224 

在一般的情況下

to[0]  = from/(256 ** (len - 1)) % 256; 
    to[1]  = from/(256 ** (len - 2)) % 256; 
    ... 
    to[len - 3] = from/(256 ** 2) % 256; 
    to[len - 2] = from/(256) % 256; 
    to[len - 1] = from/(1) % 256; 
+0

非常感謝你。 – AlbertK

+0

@AlbertK:不客氣! –