tags:

views:

567

answers:

5

If I want to represent a guid as a set of integers how would I handle the conversion? I'm thinking along the lines of getting the byte array representation of the guid and breaking it up into the fewest possible 32 bit integers that can be converted back into the original guid. Code examples preferred...

Also, what will the length of the resulting integer array be?

+1  A: 

A Guid is typically just a 128-bit number.

-- Edit

So in C#, you can get the 16 bytes via

byte[] b = Guid.NewGuid().ToByteArray();
Noon Silk
does this mean it can be represented by 4 integers eg byte[0-3] ... byte [12-15]?
grenade
Yes, indeed it does.
Noon Silk
How do we convert back a byte array to 4 integers ?
koumides
+2  A: 

Will the build-in Guid structure not suffice?

Constructor:

public Guid(
    byte[] b
)

And

public byte[] ToByteArray()

Which, returns a 16-element byte array that contains the value of this instance.

Packing the bytes into integers and visa versa should be trivial.

Philip Fourie
+7  A: 
  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);
MaLio
+4  A: 

As a GUID is just 16 bytes, you can convert it to four integers:

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

Converting back is just getting the integers as byte arrays and put together:

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

Somehow I had much more fun doing it this way:

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

and converting back:

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);
Botz3000
+1 So far, I like this the most. There's no dependencies.
grenade
Then you could mark it as answer. :D
Botz3000