private static byte[] GuidToSystemEndianBytes(Guid guid)
{
var bytes = guid.ToByteArray();
// our conversion algorithm uses 4x 32-bit unsigned ints in most-to-least significant word order
// (4 system endian) (4 system endian) (4 system endian) (4 system endian)
// but .NET GUIDs are broken up into parts and separately encoded with first 3 in system endian and last 2 in big endian
// (4 system endian)-(2 system endian)-(2 system endian)-(2 big endian)-(6 big endian)
//
// if system is little endian, we byte-swap here to build the 4 little endian words in the correct order
//
// if system is big endian, the bytes are already big endian and most-to-least significant word order
// so no swapping is necessary (and all the calculations will be done in big endian anyway)
if (BitConverter.IsLittleEndian)
{
var t = bytes[4];
bytes[4] = bytes[6];
bytes[6] = t;
t = bytes[5];
bytes[5] = bytes[7];
bytes[7] = t;
t = bytes[8];
bytes[8] = bytes[11];
bytes[11] = t;
t = bytes[9];
bytes[9] = bytes[10];
bytes[10] = t;
t = bytes[12];
bytes[12] = bytes[15];
bytes[15] = t;
t = bytes[13];
bytes[13] = bytes[14];
bytes[14] = t;
}
return bytes;
}