Why isn't Guid.ToString("n") the same as a hex string generated from a byte array of the same guid?

Dan*_*fer 13 c# hex guid

Consider the following unit test:

    [TestMethod]
    public void TestByteToString()
    {
        var guid = new Guid("61772f3ae5de5f4a8577eb1003c5c054");
        var guidString = guid.ToString("n");
        var byteString = ToHexString(guid.ToByteArray());

        Assert.AreEqual(guidString, byteString);
    }

    private String ToHexString(Byte[] bytes)
    {
        var hex = new StringBuilder(bytes.Length * 2);
        foreach(var b in bytes)
        {
            hex.AppendFormat("{0:x2}", b);
        }
        return hex.ToString();
    }
Run Code Online (Sandbox Code Playgroud)

Here's the result:

Assert.AreEqual failed. Expected:<61772f3ae5de5f4a8577eb1003c5c054>. Actual:<3a2f7761dee54a5f8577eb1003c5c054>.

Jam*_*ran 12

嗯,它们是相同的,在前4个字节之后.前四个是相同的,只是顺序相反.

基本上,当从字符串创建时,它被假定为"big-endian"格式:左边的最高字节.但是,当在内部存储(在Intel-ish机器上)时,字节按"little-endian"排序:右边的最高位字节.


dtb*_*dtb 12

如果比较结果,您可以看到前三组是相反的:

61 77 2f 3a   e5 de   5f 4a   8577eb1003c5c054
3a 2f 77 61   de e5   4a 5f   8577eb1003c5c054

那是因为在GUID结构中,这3个组被定义为DWORD两个WORD而不是字节:

{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}
Run Code Online (Sandbox Code Playgroud)

所以在内存中,英特尔处理器以Little-endian顺序存储它们(最后一个最重要的字节).