base64 to guid to base64


I’m currently researching MongoDb as a possible database option, and I’m having trouble dealing with Guid serialization. I thought at first maybe this was a bug in the C# driver’s serialization, but now I think it’s more likely a naive assumption on my part.

To help me convert the Bson base64 representations back and forth to Guids, I wrote a couple of little powershell functions to help:

An example of the issue I’m having:

And from the mongo shell:

So as you can see, the Guid I get back doesn’t match what I put in. My function and hex() return the same thing. If you compare the original to the result:


You can see that the first 3 sets of hex pairs are reversed, but the last 2 sets are not. This makes me think there is something about Guid.ToString() that I don’t understand.

Can anyone educate me please?


The order of bytes in a GUID are not the same as the order in their ToString() representation on little-endian systems.

You should use guid.ToByteArray() rather than using ToString().

And, you should use new Guid(byte[] b) to construct it, rather than $str.

To express this in pure C#:

Take a look at the “Basic Structure” section of the GUID article on Wikipedia for more details.

You will see that most of the data is stored in “Native” endianness… which is where the confusion is coming from.

To quote:

Data4 stores the bytes in the same order as displayed in the GUID text encoding (see below), but the other three fields are reversed on little-endian systems (for example Intel CPUs).


Powershell version:

As an additional caveat, you can optionally trim the “==” off of the end of your string, since it is just padding (which may help if you are trying to save space).


base64 to guid to base64 by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply