2

In order to save data traffic we want to send our GUID's as array of bytes instead of as a string (with the use of Google Protocol Buffers).

How can I convert a string representation of a GUID in Ruby to an array of bytes:

Example:

Guid: 35918bc9-196d-40ea-9779-889d79b753f0
=> Result: C9 8B 91 35 6D 19 EA 40 97 79 88 9D 79 B7 53 F0

In .NET this seems to be natively implemented: http://msdn.microsoft.com/en-us/library/system.guid.tobytearray%28v=vs.110%29.aspx

1 Answer 1

5

Your example GUID is in a Microsoft specific format. From Wikipedia:

Other systems, notably Microsoft's marshalling of UUIDs in their COM/OLE libraries, use a mixed-endian format, whereby the first three components of the UUID are little-endian, and the last two are big-endian.

So in order to get that result, we have to move the bits around a little. Specifically, we have to change the endianess of the first three components. Let's start by breaking the GUID string apart:

guid = '35918bc9-196d-40ea-9779-889d79b753f0'
parts = guid.split('-')
#=> ["35918bc9", "196d", "40ea", "9779", "889d79b753f0"]

We can convert these hex-strings to binary via:

mixed_endian = parts.pack('H* H* H* H* H*')
#=> "5\x91\x8B\xC9\x19m@\xEA\x97y\x88\x9Dy\xB7S\xF0"

Next let's swap the first three parts:

big_endian = mixed_endian.unpack('L< S< S< A*').pack('L> S> S> A*')
#=> "\xC9\x8B\x915m\x19\xEA@\x97y\x88\x9Dy\xB7S\xF0"
  • L denotes a 32-bit unsigned integer (1st component)
  • S denotes a 16-bit unsigned integer (2nd and 3rd component)
  • < and > denote little-endian and big-endian, respectively
  • A* treats the remaining bytes as an arbitrary binary string (we don't have to convert these)

If you prefer an array of bytes instead of a binary string, you'd just use:

big_endian.bytes
#=> [201, 139, 145, 53, 109, 25, 234, 64, 151, 121, 136, 157, 121, 183, 83, 240]

PS: if your actual GUID isn't Microsoft specific, you can skip the swapping part.

1
  • Hi @Stefan - about your last point: "If your actual GUID isn't Microsoft specific, you can skip the swapping part." - what do you mean by this exactly? How would I tell if a GUID I have is "Microsoft specific"? Is there some kind of tell?
    – Argus9
    Aug 19, 2021 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.