The Slicer The Slicer - 20 days ago 11x
Java Question

How to read a .NET Guid into a Java UUID

I need to communicate a Guid that was generated in .NET to a Java application. I use

to store it on disk as a
, then read it into Java and convert it to a UUID. For this purpose I copied the implementation of the (private) constructor of UUID that takes a

private UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16;
for (int i=0; i<8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i=8; i<16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
this.mostSigBits = msb;
this.leastSigBits = lsb;

However, when I inspect the UUID using
, the Java UUID is different from the .NET Guid.

For example, the .NET Guid


turns into the Java UUID


It seems that the byte ordering of the first three groups is reversed, while the ordering in the last two groups is the same.

Since I would expect the
of both the Guid and the UUID to yield the same result, does anyone know how I should correctly read the .NET Guid into a Java UUID?

Edit: To clarify, the implementation is not my own. It is the private constructor of the
class that takes a
, which I copied to use for the purpose of reading a byte[] from disk into a UUID.

I do not want to use strings to store the Guids as I'm storing a lot of them and it seems like a waste of space.

Russell Troywest's link at least clarifies why the first couple of groups of the Guid come out reversed, while the second half stays in the same order. The question is, can I depend on .NET always generating these bytes in the same order?


In response to your edit, no, you cannot consistently depend on the bytes being generated in the same order. The runtime determines the endianness. C# does however offer BitConverter.isLittleEndian for this very reason.

I know you can't change the endianness of the Java implementation and the bit shifting. But you can shift the bits on the C# end after storing and before sending them to Java.


MSDN Article on IsLittleEndian

Edit: To be practical, you can PROBABLY count on it always being little endian in its layout of the first chunk of bytes, but technically you can't.