1

I am having troubles converting GUIDs to gRPC/protobuf-net bcl-Guids (bcl.proto with Guid definition).

I did find two artilces such as: Harmonize protobuf-net bcl.Guid's HI/LO with sql uniqueidentifiers for correlated subquerying? or https://stackoverflow.com/a/6670210/109951 but it turns out, that those answers are not working correctly for some Guids.

So here is my code in .NET Framework 4.7.2:

private void SetHighLow(Guid guid)
{
    long[] longs = new long[2];
    byte[] bytes = guid.ToByteArray();
    longs[0] = BitConverter.ToInt64(bytes, 0);
    longs[1] = BitConverter.ToInt64(bytes, 8);
    textBoxGuidLo.Text = longs[0].ToString();
    textBoxGuidHi.Text = longs[1].ToString();
}

These GUIDs work fine for example:

  • 63b6ce49-51a6-45b0-8304-cd2b64644419 ➡️ lo: 5021603359597448777, hi: 1820690530758886531
  • 34fd7e06-6f44-4fc3-925b-472d3c19d677 ➡️ lo: 5747559888192372230, hi: 8635117081777888146

These GUIDs result into negative hi values and are not being calculated back correctly:

  • c0dbb1b2-0a21-40fb-925b-472d3c19d677 ➡️ lo: 4682347377667584434,hi: -3098910154901023072
  • 88e052a2-8873-42b8-a62a-e858abef10e5 ➡️ lo: 4807742632017023650,hi: -1940787920186627418

Any ideas?

DominikAmon
  • 892
  • 1
  • 14
  • 26

1 Answers1

0

I did find the solution, as @JonasH pointed me in the right the direction:

private void SetHighLow(Guid guid)
{
    byte[] bytes = guid.ToByteArray();
    ulong[] longs = new ulong[2];
    longs[0] = BitConverter.ToUInt64(bytes, 0);
    longs[1] = BitConverter.ToUInt64(bytes, 8);
    textBoxGuidLo.Text = longs[0].ToString();
    textBoxGuidHi.Text = longs[1].ToString();
    textBoxGuidGrpc.Text = String.Format(HiLoJsonFormat, longs[0], longs[1]);
}

Using ToUInt64 instead of ToInt64 did do the trick.

For those looking for the other direction:

ulong low = Convert.ToUInt64(textBoxGuidLo.Text);
ulong high = Convert.ToUInt64(textBoxGuidHi.Text);

uint a = (uint)(low >> 32), b = (uint)low, c = (uint)(high >> 32), d = (uint)high;
return new Guid((int)b, (short)a, (short)(a >> 16),
                (byte)d, (byte)(d >> 8), (byte)(d >> 16), (byte)(d >> 24),
                (byte)c, (byte)(c >> 8), (byte)(c >> 16), (byte)(c >> 24));
DominikAmon
  • 892
  • 1
  • 14
  • 26