为什么 Guid.ToString(“n”) 与从相同 guid 的字节数组生成的十六进制字符串不同?
考虑以下单元测试:
[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();
}
结果如下:
Assert.AreEqual 失败。预期:<61772f3ae5de5f4a8577eb1003c5c054>。实际:<3a2f7761dee54a5f8577eb1003c5c054>。
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();
}
Here's the result:
Assert.AreEqual failed. Expected:<61772f3ae5de5f4a8577eb1003c5c054>. Actual:<3a2f7761dee54a5f8577eb1003c5c054>.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,在前 4 个字节之后,它们是相同的。前四个是一样的,只是顺序相反。
基本上,当从字符串创建时,假定它采用“big-endian”格式:最高字节在左边。但是,当在内部存储时(在 Intel-ish 机器上),字节按“little-endian”排序:最高位字节在右侧。
Well, they are the same, after the first 4 bytes. And the first four are the same, just in the reverse order.
Basically, when created from the string, it's assumed to be in "big-endian" format: Highest byte to the left. However, when stored internally (on an Intel-ish machine), the bytes are ordered "little-endian": highest order byte to the right.
如果比较结果,您可以看到前三组是相反的:
那是因为在 GUID 结构,这 3 组被定义为
DWORD
和两个WORD
而不是字节:因此,在内存中,英特尔处理器以 Little-endian 顺序存储它们(最高有效字节在最后)。
If you compare the results, you can see that the first three groups are reversed:
That's because in the GUID structure, these 3 groups are defined as
DWORD
and twoWORD
s rather than bytes:so in memory, an Intel processor stores them in Little-endian order (the most significant byte the last).
GUID 的结构如下:
因此,对于
a
表示的部分,您的代码会反转字节。所有其他部分均已正确转换。A GUID is structured as follows:
So for the part represented by
a
your code gets the bytes reversed. All other parts are transformed correctly.