9

I was thinking about GUIDs recently, which led me to try this code:

Guid guid = Guid.NewGuid(); Console.WriteLine(guid.ToString()); //prints 6d1dc8c8-cd83-45b2-915f-c759134b93aa Console.WriteLine(BitConverter.ToString(guid.ToByteArray())); //prints C8-C8-1D-6D-83-CD-B2-45-91-5F-C7-59-13-4B-93-AA bool same=guid.ToString()==BitConverter.ToString(guid.ToByteArray()); //false Console.WriteLine(same); 

You can see that all of the bytes are there, but half of them are in the wrong order when I use BitConverter.ToString. Why is this?

4
  • blind guess: BitConverter & ByteArray doesn't work well together? Commented Dec 14, 2015 at 13:04
  • 1
    guid.ToByteArray() Returns a 16-element byte array that contains the value of this instance. Commented Dec 14, 2015 at 13:05
  • msdn.microsoft.com/en-us/library/… Commented Dec 14, 2015 at 13:05
  • 1
    "half of them are in the wrong order" - wrong depends on what you think is the right order. The bytes are printed in a different order - that would be more true. And it would directly lead to the question, what might be the reason? Good terminology is half way to the solution. Commented Dec 14, 2015 at 13:05

1 Answer 1

11

As per the Microsoft documentation:

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. The example provides an illustration.

using System; public class Example { public static void Main() { Guid guid = Guid.NewGuid(); Console.WriteLine("Guid: {0}", guid); Byte[] bytes = guid.ToByteArray(); foreach (var byt in bytes) Console.Write("{0:X2} ", byt); Console.WriteLine(); Guid guid2 = new Guid(bytes); Console.WriteLine("Guid: {0} (Same as First Guid: {1})", guid2, guid2.Equals(guid)); } } // The example displays the following output: // 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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.