Home » Php » 16 bytes binary form of canonical uuid representation in php

16 bytes binary form of canonical uuid representation in php

Posted by: admin July 12, 2020 Leave a comment


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



How to&Answers:
 $bin = pack("h*", str_replace('-', '', $guid));



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(substr($uuid, 0, 8),
                                                        substr($uuid, 9, 4), substr($uuid, 14, 4),
                                                        substr($uuid, 19, 2), substr($uuid, 21, 2))),
                                                  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.