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

2 Answers 2

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

pack

Sign up to request clarification or add additional context in comments.

2 Comments

Reverse conversion could also be useful : stackoverflow.com/a/2839147/536308
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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.