PHP从MS sql读取二进制UID值为Hex

时间:2012-08-13 03:11:41

标签: php hex uid

我有一个生成UID的代码:

        $time_low = str_pad(dechex(mt_rand(0, 65535)), 4, '0', STR_PAD_LEFT) . str_pad(dechex(mt_rand(0, 65535)), 4, '0', STR_PAD_LEFT);
        $time_mid = str_pad(dechex(mt_rand(0, 65535)), 4, '0', STR_PAD_LEFT);

        $time_high_and_version = mt_rand(0, 255);
        $time_high_and_version = $time_high_and_version & hexdec('0f');
        $time_high_and_version = $time_high_and_version ^ hexdec('40');  // Sets the version number to 4 in the high byte
        $time_high_and_version = str_pad(dechex($time_high_and_version), 2, '0', STR_PAD_LEFT);

        $clock_seq_hi_and_reserved = mt_rand(0, 255);
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved & hexdec('3f');
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved ^ hexdec('80');  // Sets the variant for this GUID type to '10x'
        $clock_seq_hi_and_reserved = str_pad(dechex($clock_seq_hi_and_reserved), 2, '0', STR_PAD_LEFT);

        $clock_seq_low = str_pad(dechex(mt_rand(0, 65535)), 4, '0', STR_PAD_LEFT);
        $node = str_pad(dechex(mt_rand(0, 65535)), 4, '0', STR_PAD_LEFT) . str_pad(dechex(mt_rand(0, 65535)), 4, '0', STR_PAD_LEFT) . str_pad(dechex(mt_rand(0, 65535)), 4, '0', STR_PAD_LEFT);
        $guid = $time_low . '-' . $time_mid . '-' . $time_high_and_version . $clock_seq_hi_and_reserved . '-' . $clock_seq_low . '-' . $node;

它生成一个字符串,如: 011FFF33-CA4A-44E8-8CD5-7344D8E94344 。当我从MS SQL 2008数据库中读取它时,我得到二进制字符串,如:3ÿJÊèDŒÕsDØéCD。如何将其读作十六进制字符串而不是二进制字符串?谢谢!

1 个答案:

答案 0 :(得分:0)

将它转换为select调用中的字符串 - uid存储在原始位中,而不是您看到的漂亮的十六进制字符串。 mssql驱动程序可能正在传回那些原始位而不是转换为可读的十六进制字符串本身,所以在查询中这样做。