Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guid Byte Order in .NET

Tags:

I am creating a GUID like this

Guid g = new Guid(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF }); Console.WriteLine(g); 

This outputs

03020100-0504-0706-0809-0a0b0c0d0e0f 

According to Wikipedia there are four parts in the guid and this explains why the bytes order switch in four groups. However the Wikipedia article also states that all parts are stored in Big Endian format. Obviously the first three parts are not Big Endian. The GetBytes() method of the guid returns the bytes in the very same order used for creation. What is the explaination for this behavior?

like image 442
Stilgar Avatar asked Apr 17 '12 11:04

Stilgar


People also ask

How many bytes is a GUID C#?

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required.

Is a 16 byte GUID?

A GUID is a 128-bit integer (16 bytes) value. That means that there are more than 300, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000 different values.


1 Answers

It appears that MS are storing the five parts in a structure. The first 4 parts are either 2 or 4 bytes long and are therefore probably stored as a native type (ie. WORD and DWORD) in little endian format. The last part is 6 bytes long and it therefore handled differently (probably an array).

Does the Spec state that the GUID is stored in big-endian order, or that the storage of parts are in that order but the indiviual parts may be implementation specific?

EDIT:

From the UUID spec, section 4.1.2. Layout and Byte Order (emphasis mine):

To minimize confusion about bit assignments within octets, the UUID
record definition is defined only in terms of fields that are
integral numbers of octets. The fields are presented with the most
significant one first.

...

In the absence of explicit application or presentation protocol
specification to the contrary
, a UUID is encoded as a 128-bit object, as follows:

The fields are encoded as 16 octets, with the sizes and order of the fields defined above, and with each field encoded with the Most Significant Byte first (known as network byte order).

It might be that MS have stored the bytes in the correct order, but have not bothered to network-to-host order the WORD and DWORD parts for presentation (which appears to be ok according to the spec, at least by my unskilled reading of it.)

like image 145
Grhm Avatar answered Oct 20 '22 02:10

Grhm