将Guid表示为一组整数
如果我想将guid表示为一组整数,我将如何处理转换? 我正在考虑获取guid的字节数组表示并将其分解为最少可能转换回原始guid的32位整数。 代码示例首选…
此外,结果整数数组的长度是多少?
不知怎的,我这样做有很多乐趣:
byte[] bytes = guid.ToByteArray(); int[] ints = new int[bytes.Length / sizeof(int)]; for (int i = 0; i < bytes.Length; i++) { ints[i / sizeof(int)] = ints[i / sizeof(int)] | (bytes[i] << 8 * ((sizeof(int) - 1) - (i % sizeof(int)))); }
并转回:
byte[] bytesAgain = new byte[ints.Length * sizeof(int)]; for (int i = 0; i < bytes.Length; i++) { bytesAgain[i] = (byte)((ints[i / sizeof(int)] & (byte.MaxValue << 8 * ((sizeof(int) - 1) - (i % sizeof(int))))) >> 8 * ((sizeof(int) - 1) - (i % sizeof(int)))); } Guid guid2 = new Guid(bytesAgain);
System.Guid guid = System.Guid.NewGuid(); byte[] guidArray = guid.ToByteArray(); // condition System.Diagnostics.Debug.Assert(guidArray.Length % sizeof(int) == 0); int[] intArray = new int[guidArray.Length / sizeof(int)]; System.Buffer.BlockCopy(guidArray, 0, intArray, 0, guidArray.Length); byte[] guidOutArray = new byte[guidArray.Length]; System.Buffer.BlockCopy(intArray, 0, guidOutArray, 0, guidOutArray.Length); System.Guid guidOut = new System.Guid(guidOutArray); // check System.Diagnostics.Debug.Assert(guidOut == guid);
由于GUID只有16个字节,您可以将其转换为四个整数:
Guid id = Guid.NewGuid(); byte[] bytes = id.ToByteArray(); int[] ints = new int[4]; for (int i = 0; i < 4; i++) { ints[i] = BitConverter.ToInt32(bytes, i * 4); }
转换回来只是将整数作为字节数组并放在一起:
byte[] bytes = new byte[16]; for (int i = 0; i < 4; i++) { Array.Copy(BitConverter.GetBytes(ints[i]), 0, bytes, i * 4, 4); } Guid id = new Guid(bytes);
内置Guid结构是不够的?
构造函数:
public Guid( byte[] b )
和
public byte[] ToByteArray()
其中,返回包含此实例值的16元素字节数组。
将字节打包成整数,反之亦然应该是微不足道的。
Guid通常只是一个128位的数字。
– 编辑
所以在C#中,你可以通过16个字节获得
上述就是C#学习教程:将Guid表示为一组整数分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
byte[] b = Guid.NewGuid().ToByteArray();
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/950241.html