2

If I have a UUID string like the following:

217aad3b-0b3d-4df0-a9ee-4fc9708f40bd

How do I pack that into a byte array (16 bytes) so that I can send it over HTTP as binary data?

Given the byte array, what is the function that unpacks it into a string like the one above?

3
  • I don't think that's possible: In ruby, chars are one byte a piece. ("puts 'a'.bytesize"). The UUID has 36 chars, so it will never fit in an 16 byte array.
    – Stobbej
    Commented Jul 10, 2014 at 19:54
  • Ruby defaults to UTF-8 now, so chars are multi-byte when they are necessary: 'é'.bytesize # => 2. That probably won't help the OP though. Commented Jul 10, 2014 at 21:16
  • 1
    A UUID is a 128 bit value, not a string. A string representation of the UUID in hexadecimal might take up 36 bytes, but most of those bits are "wasted space." 128 bits/8 bits = 16 bytes. Commented Nov 7, 2015 at 23:09

1 Answer 1

13

You can use Array.pack to pack your string:

First you need to turn it to array of 16-bit integers:

num_arr = "217aad3b-0b3d-4df0-a9ee-4fc9708f40bd".scan(/[0-9a-f]{4}/).map { |x| x.to_i(16) }
# => [8570, 44347, 2877, 19952, 43502, 20425, 28815, 16573]

Then pack it:

packed = num_arr.pack('n*')
# => "!z\xAD;\v=M\xF0\xA9\xEEO\xC9p\x8F@\xBD"
packed.bytesize
# => 16

packed is a string, but in Ruby byte arrays are represented as strings.

1
  • 3
    Note that the above, while a byte representation of a GUID, is not the correct byte representation of a GUID. If you use C# to get the byte representation of the GUID with Guid.Parse("217aad3b-0b3d-4df0-a9ee-4fc9708f40bd").ToByteArray().Select (b => b.ToString("X")) you will notice that the bytes are 3B AD 7A 21 3D B F0 4D A9 EE 4F C9 70 8F 40 BD - in Ruby this would be ";\xADz!=\v\xF0M\xA9\xEEO\xC9p\x8F@\xBD" - note that the above answer incorrectly packs the byte endian-ness if you're looking for a valid byte string to use when making API calls against the Win32 API for instance. Commented Dec 20, 2016 at 1:58

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.