[ACCEPTED]-base64 to guid to base64-guid

Accepted answer
Score: 13

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

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

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

To express this in pure C#:

public string GuidToBase64(Guid guid)
    return System.Convert.ToBase64String(guid.ToByteArray());  // Very similar to what you have.

public Guid Base64Toguid(string base64)
    var bytes = System.Convert.FromBase64String(base64);
    return new Guid(bytes);  // Not that I'm not building up a string to represent the GUID.

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

You 12 will see that most of the data is stored 11 in "Native" endianness... which 10 is where the confusion is coming from.

To 9 quote:

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


Powershell version:

function base64toguid  
    $b = [System.Convert]::FromBase64String($str);
    $g = new-object -TypeName System.Guid -ArgumentList (,$b);
    return $g;

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

Score: 2

You need to call the Guid constructor that 6 takes a byte array. There's special syntax 5 needed for that in Powershell - if you just 4 pass $b it will tell you it can't find a 3 constructor that takes 16 arguments, so 2 you have to wrap the byte array in another 1 array:

$g = new-object -TypeName System.Guid -ArgumentList (,$b)
Score: 0

Looking at the c-sharp driver documentation on the mongo website, it 12 turns out that there is an implicit conversion 11 provided for System.Guid.

So in c# (sorry, my 10 powershell is a little rusty), you would 9 just write:

Guid g = Guid.NewGuid(); //or however your Guid is initialized
BsonValue b = g;

I imagine that the reverse will 8 probably also work:

BsonValue b = // obtained this from somewhere
Guid g = b;

If you have no specific 7 need to serialize the Guid as base64, then 6 converting directly to binary will be much 5 less work (note that there will be no endian 4 issues, for example). Also, the data will 3 be stored in binary on the server, so it 2 will be more space efficient than using 1 base64.

More Related questions