-1

How does Guid.ToByteArray() work in c#.Can someone help me understand how does the following Guid token gets converted to ByteArray.

 Guid: 35918bc9-196d-40ea-9779-889d79b753f0
 guid.toByteArray: C9 8B 91 35 6D 19 EA 40 97 79 88 9D 79 B7 53 F0
Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
  • See the "Encoding" section in the [Wikipedia article](https://en.wikipedia.org/wiki/Universally_unique_identifier) – Klaus Gütter Jan 03 '22 at 07:58
  • 1
    https://github.com/dotnet/corert/blob/master/src/System.Private.CoreLib/shared/System/Guid.cs – fbede Jan 03 '22 at 08:00
  • 1
    The documentation says "Note that the order of bytes in the returned byte array is different from the string representation of a Guid value. The order of the beginning four-byte group and the next two two-byte groups is reversed, whereas the order of the last two-byte group and the closing six-byte group is the same." Is there something unclear about how the text and byte forms represent the same GUID? – Lance U. Matthews Jan 03 '22 at 08:08
  • 2
    Does this answer your question? [Why does Guid.ToByteArray() order the bytes the way it does?](https://stackoverflow.com/questions/9195551/why-does-guid-tobytearray-order-the-bytes-the-way-it-does) or [C# - why does System.Guid flip the bytes in a byte array?](https://stackoverflow.com/q/45671415/150605) – Lance U. Matthews Jan 03 '22 at 08:14
  • Are you asking how the code actually works, or are you asking how the GUID translates to that byte array? – Lasse V. Karlsen Jan 03 '22 at 08:15
  • @LasseV.Karlsen I am asking How the GUID translates to that array. Asking this because I need to create my own implementation in javascript. Given the byte form, I need to generate the original GUID. – Madhu Kumar Tallapalli Jan 03 '22 at 09:12
  • 1
    So then just see where each 2-digit byte landed in the array from the example you gave, shouldn't be that hard, and @LanceU.Matthews also explained how it works above. – Lasse V. Karlsen Jan 03 '22 at 09:16

1 Answers1

2

A guid is essentially just a 128-bit number. Internally this is represented as one 32-bit int, two 16-bit ints and eight 8-bit ints.

So conversion to a byte array is essentially just creating an array, and using shifting to select the correct byte in the 16 & 32-bit ints.

JonasH
  • 28,608
  • 2
  • 10
  • 23