Introduce Guid as a set of integers

If I want to represent guid as a set of integers, how would I handle the conversion? I am thinking about how to get a representation of the guid byte array and break it down into the smallest possible 32-bit integers that can be converted back to the original guid. Preferred code examples ...

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

+3
source share
5 answers

Somehow it was much more interesting to me to do it like this:

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 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);
+4
source
  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
source

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

Will the built-in Guid structure be built?

Constructor:

public Guid(
    byte[] b
)

AND

public byte[] ToByteArray()

That returns an array of 16 elements that contains the value of this instance.

Packing bytes into integers and vice versa should be trivial.

+2
source

A Guid is usually just a 128-bit number.

- Change

So in C # you can get 16 bytes through

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

Source: https://habr.com/ru/post/1716420/


All Articles