grenade
grenade

Reputation: 32169

Represent a Guid as a set of integers

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?

Upvotes: 4

Views: 4947

Answers (5)

Botz3000
Botz3000

Reputation: 39630

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

Upvotes: 4

Guffa
Guffa

Reputation: 700630

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

Upvotes: 6

MaLio
MaLio

Reputation: 2540

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

Upvotes: 5

Philip Fourie
Philip Fourie

Reputation: 116997

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.

Upvotes: 2

Noon Silk
Noon Silk

Reputation: 55152

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

Upvotes: 1

Related Questions