Convert binary UUID to readable HEX string in PHP
I've been almost ripping my hair out tonight! I was setting PHP up to connecting via FreeTDS to a MS SQL Server and has quite some problems running stored procedures...
First thing is that FreeTDS needs to have the server and version number changed in the configuration file - else it just gave an obscure error message (thanks Google!).
Secondly I was getting slightly annoyed with MSSQL way of storing UUID's (uniqueidentifier) as binary(16) in the DB. In our days, I'd say this is more annoying than useful... and I couldn't get the conversion right. And good old Goolgle wasn't able to help.
All I noticed was that various PHP built-in conversions didn't give me the right string... but finally (after actually looking at the converted hex), I noticed that it was only in the beginning it was not matching! And then I quickly relalised that there was some rather odd byte swapping in the beginning, but not in the end.
So here goes:
function bin2uuidString($str) {
$str = bin2hex($str);
return strtoupper(substr($str,6,2). //First 4 hex pairs are swapped back to front
substr($str,4,2).
substr($str,2,2).
substr($str,0,2).'-'.
substr($str,10,2). //Same with next 2 pairs
substr($str,8,2).'-'.
substr($str,14,2). //Same with next 2 pairs
substr($str,12,2).'-'.
substr($str,16,4).'-'. //Stays, no swap
substr($str,20,12)); //Stays, no swap
}
Enjoy! :o)
First thing is that FreeTDS needs to have the server and version number changed in the configuration file - else it just gave an obscure error message (thanks Google!).
Secondly I was getting slightly annoyed with MSSQL way of storing UUID's (uniqueidentifier) as binary(16) in the DB. In our days, I'd say this is more annoying than useful... and I couldn't get the conversion right. And good old Goolgle wasn't able to help.
All I noticed was that various PHP built-in conversions didn't give me the right string... but finally (after actually looking at the converted hex), I noticed that it was only in the beginning it was not matching! And then I quickly relalised that there was some rather odd byte swapping in the beginning, but not in the end.
So here goes:
function bin2uuidString($str) {
$str = bin2hex($str);
return strtoupper(substr($str,6,2). //First 4 hex pairs are swapped back to front
substr($str,4,2).
substr($str,2,2).
substr($str,0,2).'-'.
substr($str,10,2). //Same with next 2 pairs
substr($str,8,2).'-'.
substr($str,14,2). //Same with next 2 pairs
substr($str,12,2).'-'.
substr($str,16,4).'-'. //Stays, no swap
substr($str,20,12)); //Stays, no swap
}
Enjoy! :o)
Etiketter: PHP UUID binary HEX uniqueidentifier