2

Guid.ToByteArray() change the position of the first bytes. Why does this method do this? I want to parse a Base64 string to a byte array in the same form.

Look at this example1:

Guid guid = Guid.NewGuid();
Console.WriteLine($"Guid: {guid}");
var bytes = guid.ToByteArray();
foreach (var byt in bytes)
    Console.Write($"{byt:X2} ");

Console.WriteLine();
var guid2 = new Guid(bytes);
Console.WriteLine($"Guid: {guid2} (Same as First Guid: {guid2.Equals(guid)})");

// The example displays output similar to the following:
//
//    Guid: 35918bc9-196d-40ea-9779-889d79b753f0
//    C9 8B 91 35 6D 19 EA 40 97 79 88 9D 79 B7 53 F0
//    Guid: 35918bc9-196d-40ea-9779-889d79b753f0 (Same as First Guid: True)

I also tried Encoding.GetBytes()2, but that doesn't work either.

[1] https://learn.microsoft.com/en-us/dotnet/api/system.guid.tobytearray?view=net-8.0

[2] https://learn.microsoft.com/de-de/dotnet/api/system.text.encoding.getbytes?view=net-7.0

sjakobi
  • 3,546
  • 1
  • 25
  • 43
Dominik Teroerde
  • 309
  • 1
  • 11
  • 1
    Source is here, but I can't explain: https://referencesource.microsoft.com/#mscorlib/system/guid.cs,892 – DaveShaw May 04 '23 at 08:18
  • 7
    Because historically the [parts had a specific meaning, and therefore also a specific storage layout with specific endianness](https://devblogs.microsoft.com/oldnewthing/20220928-00/?p=107221). This doesn't apply to today's more common version 4 GUIDs (which are fully random) but the layout remains. – Jeroen Mostert May 04 '23 at 08:22

0 Answers0