在处理mysql协议时或一些二进制流(pack生成),经常用一1,N个字字来表示长度,需做如下转化
1 2 3 4 5 6 7 8 9 10 11 12 |
// test one $length = substr($data, 0, 1); $length = bin2hex($length); $length = hexdec($length); // test two $len = 192; $byte = pack("C", $len); $len = bin2hex($byte); $len = hexdec($len); echo "length:" . $len ."\n"; |
参考:http://blog.csdn.net/wind520/article/details/43964821
mysql client验证报文解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// 包长 $length = substr($data, 0, 1); $length = bin2hex($length); $length = hexdec($length); echo $length . "\n"; // 登录用户名 $body = substr($data, 36); $userName = $this->getChars($body); $i = strlen($userName) + 1; echo $userName . "\n"; // 数据库名[可选] $lengthByte = substr($body, $i, 1); $len = bin2hex($lengthByte); $len = hexdec($len); echo $len . "\n"; if($len <= 250){ $i = $i + $len + 1; $dbName = $this->getChars($body, $i); echo $dbName . "\n"; } protected function getChars($data, $start = 0){ $i = $start; $length = strlen($data); while($i < $length){ $char = substr($data, $i, 1); if(ord($char) === 0){ return substr($data, $start, $i - $start); } $i++; } return $data; } |