2017-08-14 74 views
1

當進入下面的代碼到C#即時窗口,它產生一些不尋常的結果,這是我只能假設是因爲內部,System.Guid翻轉一定字節數:爲什麼System.Guid翻轉字節數組中的字節?

當使用從0序字節數組15

new Guid(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}) 
[03020100-0504-0706-0809-0a0b0c0d0e0f] 

當使用帶值的非順序的字節數組0-15

new Guid(new byte[] {3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15}) 
[00010203-0405-0607-0809-0a0b0c0d0e0f] 

爲什麼前3組翻轉?

+0

大端,小端。英特爾設計微處理器的方式決定了字節順序。英特爾在那裏設計了micro的速度和交換字節順序,使得微型計算機運行更快。微軟只是遵循了英特爾規範。 – jdweng

+0

另請參閱https://stackoverflow.com/questions/9195551/why-does-guid-tobytearray-order-the-bytes-the-way-it-does?rq=1 – schnaader

回答

2

發現在Wikipedia關於UUID。

其他系統,特別是微軟在他們的COM/OLE庫的UUID編組,使用混合-endian格式,從而使UUID的前三個部分都是小端的,最後兩個是大端。

例如,00112233-4455-6677-8899-AABBCCDDEEFF被編碼爲字節33 22 11 00 55 44 77 66 88 99 AA BB CC DD EE FF

1

前4字節的塊屬於一個Int32值,因爲byte order,接下來的2個塊屬於Int16值,它們被分配給Guid。也許你應該嘗試具有匹配整數數據類型作爲參數,並且給出了更直觀的排序中other constructor

Guid g = new Guid(0xA, 0xB, 0xC, 
        new Byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }); 
Console.WriteLine("{0:B}", g); 
// The example displays the following output: 
//  {0000000a-000b-000c-0001-020304050607} 
1

看那source code of Guid.cs看到它背後的結構:

// Represents a Globally Unique Identifier. 
public struct Guid : IFormattable, IComparable, 
        IComparable<Guid>, IEquatable<Guid> { 
    // Member variables 
    private int   _a; // <<== First group, 4 bytes 
    private short  _b; // <<== Second group, 2 bytes 
    private short  _c; // <<== Third group, 2 bytes 
    private byte  _d; 
    private byte  _e; 
    private byte  _f; 
    private byte  _g; 
    private byte  _h; 
    private byte  _i; 
    private byte  _j; 
    private byte  _k; 
    ... 
} 

正如你所看到的,內部Guid由一個32位整數,兩個16位整數和8個獨立字節組成。在little-endian architectures之後的第一個int和跟隨它的兩個short的字節以相反的順序存儲。其餘八個字節的順序保持不變。

相關問題