2017-08-14 52 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的字节以相反的顺序存储。其余八个字节的顺序保持不变。

相关问题