10

how can I get 16 bytes binary form of the uuid from its string/canonical representation:

ex:1968ec4a-2a73-11df-9aca-00012e27a270

cheers, /Marcin

codaddict
  • 445,704
  • 82
  • 492
  • 529
Marcin
  • 5,469
  • 15
  • 55
  • 69

2 Answers2

17
 $bin = pack("h*", str_replace('-', '', $guid));

pack

user187291
  • 53,363
  • 19
  • 95
  • 127
  • 3
    Reverse conversion could also be useful : http://stackoverflow.com/a/2839147/536308 – ıɾuǝʞ Mar 02 '12 at 11:39
  • Note that you need to be careful about byte order (endianness) if your binary value has to be interoperable with other software. Different specifications are not consistent with respect to the interpretation of the text fields; see [this](http://howtowriteaprogram.blogspot.ca/2009/03/uuid-and-byte-order.html). – Kevin Aug 20 '13 at 05:53
2

If you read accurately the chapter about the format and string representation of a UUID as defined by DCE then you can't naively treat the UUID string as a hex string, see String Representation of UUIDs (which is referenced from the Microsoft Developer Network). I.e. because the first three fields are represented in big endian (most significant digit first).

So the most accurate way (and probably the fastest) on a little endian system running PHP 32bit is:

$bin = call_user_func_array('pack',
                            array_merge(array('VvvCCC6'),
                                        array_map('hexdec',
                                                  array(substr($uuid, 0, 8),
                                                        substr($uuid, 9, 4), substr($uuid, 14, 4),
                                                        substr($uuid, 19, 2), substr($uuid, 21, 2))),
                                        array_map('hexdec',
                                                  str_split(substr($uuid, 24, 12), 2))));

It splits the string into fields, turns the hex representation into decimal numbers and then mangles them through pack.

Because I don't have access to a big endian architecture, I couldn't verify whether this works or one has to use e.g. different format specifiers for pack.

klaus triendl
  • 1,237
  • 14
  • 25