为什么Guid.ToString(" n")与从相同guid的字节数组生成的十六进制字符串相同? [英] Why isn't Guid.ToString("n") the same as a hex string generated from a byte array of the same guid?

查看:208
本文介绍了为什么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);

$ b private String ToHexString(Byte [] bytes)
{
var hex = new StringBuilder(bytes.Length * 2);
foreach(var b以字节为单位)
{
hex.AppendFormat({0:x2},b);
}
return hex.ToString();
}

结果如下:

Assert.AreEqual失败。预期:其中61772f3ae5de5f4a8577eb1003c5c054取代。实际:< 3a2f7761dee54a5f8577eb1003c5c054>。

解决方案

好了,他们是一样的,字节。前四个是相同的,只是以相反的顺序。

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

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>.

解决方案

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.ToString(&quot; n&quot;)与从相同guid的字节数组生成的十六进制字符串相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆