2009-08-30 35 views
3

如果我想將guid表示爲一組整數,我將如何處理轉換?我正在考慮獲取guid的字節數組表示形式,並將其分解爲可以轉換回原始guid的最少32位整數。代碼示例首選...將Guid表示爲一組整數

另外,生成的整數數組的長度是多少?

回答

4

不知怎的,我這樣做更有趣:

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); 
+1

+1到目前爲止,我最喜歡這個。沒有依賴關係。 – grenade 2009-08-30 18:42:17

+0

然後您可以將其標記爲答案。 :d – Botz3000 2009-08-30 20:13:25

1

Guid通常只是一個128位數字。

- 編輯

所以在C#中,您可以通過

byte[] b = Guid.NewGuid().ToByteArray(); 
+0

這是否意味着它可以通過4個整數表示如字節[0-3] ...字節[12-15] – grenade 2009-08-30 10:36:40

+1

是的,的確如此。 – 2009-08-30 10:37:42

+0

我們如何將字節數組轉換爲4個整數? – koumides 2010-08-18 15:30:28

2

得到16個字節將集結在的Guid結構還不夠?

構造:

public Guid(
    byte[] b 
) 

而且

public byte[] ToByteArray() 

其中,返回包含此實例的值的16個元素的字節數組。

將字節包裝成整數,反之亦然應該是微不足道的。

5
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); 
5

爲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); 
+0

爲什麼downvote?如果你不解釋你認爲是錯誤的,它不能改善答案。 – Guffa 2012-01-05 11:50:22

+0

這實現了結果,但使用了具有Endianness問題的BitConverter – 2014-10-27 11:50:37

+0

@SuryaPratap:然後你必須澄清爲什麼你認爲這是一個問題。 – Guffa 2014-10-27 19:21:02