如果我想將guid表示爲一組整數,我將如何處理轉換?我正在考慮獲取guid的字節數組表示形式,並將其分解爲可以轉換回原始guid的最少32位整數。代碼示例首選...將Guid表示爲一組整數
另外,生成的整數數組的長度是多少?
如果我想將guid表示爲一組整數,我將如何處理轉換?我正在考慮獲取guid的字節數組表示形式,並將其分解爲可以轉換回原始guid的最少32位整數。代碼示例首選...將Guid表示爲一組整數
另外,生成的整數數組的長度是多少?
不知怎的,我這樣做更有趣:
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);
得到16個字節將集結在的Guid結構還不夠?
構造:
public Guid(
byte[] b
)
而且
public byte[] ToByteArray()
其中,返回包含此實例的值的16個元素的字節數組。
將字節包裝成整數,反之亦然應該是微不足道的。
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);
+1到目前爲止,我最喜歡這個。沒有依賴關係。 – grenade 2009-08-30 18:42:17
然後您可以將其標記爲答案。 :d – Botz3000 2009-08-30 20:13:25