如果我想将guid表示为一组整数,我将如何处理转换?我正在考虑获取guid的字节数组表示并将其分解为最少可能转换回原始guid的32位整数.代码示例首选...
此外,结果整数数组的长度是多少?
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);
Run Code Online (Sandbox Code Playgroud)
由于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);
}
Run Code Online (Sandbox Code Playgroud)
转换回来只是将整数作为字节数组并放在一起:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3730 次 |
| 最近记录: |