如何组合两个GUID值

2 guid

我想组合两个guid值并生成一个32位的字母数字值(可以通过使用散列来完成).

小智 9

不漂亮,但它有效..

 private static Guid MungeTwoGuids(Guid guid1, Guid guid2)
 {
     const int BYTECOUNT = 16;
     byte[] destByte = new byte[BYTECOUNT];
     byte[] guid1Byte = guid1.ToByteArray();
     byte[] guid2Byte = guid2.ToByteArray();

     for (int i = 0; i < BYTECOUNT; i++)
     {
         destByte[i] = (byte) (guid1Byte[i] ^ guid2Byte[i]);
     }
      return new Guid(destByte);
 }
Run Code Online (Sandbox Code Playgroud)

是的,在我的情况下,我可以处理非独特保证


小智 8

如何将Guids分成两个8字节的块,将它们转换为ulong(8字节),XOR将它们组合起来然后连接2个结果.

public static Guid Combine(this Guid x, Guid y)
        {
            byte[] a = x.ToByteArray();
            byte[] b = y.ToByteArray();

            return new Guid(BitConverter.GetBytes(BitConverter.ToUInt64(a, 0) ^ BitConverter.ToUInt64(b, 8))
                .Concat(BitConverter.GetBytes(BitConverter.ToUInt64(a, 8) ^ BitConverter.ToUInt64(b, 0))).ToArray());
        }
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是,在建议的实现中,A XOR B 不等于 B XOR A (2认同)

Ric*_*ard 1

取决于平台和您想要执行的操作的详细信息。

在 .NET/C# 中,您可以采用非常简单的方法:

var result = g1.GetHashCode() ^ g2.GetHashCode();
Run Code Online (Sandbox Code Playgroud)