我试图从字符串中提取打包的十六进制数字。我的应用程序正在与一个服务器进行通信,该服务器发送一个带有一个标题的字符串,后跟2个字节的十六进制数字这个字符串中有数千个数字。
我想要做的是提取每个2字节的压缩数字,并将其转换为我可用于执行计算的数字。
例如:string = "info:\x00\x00\x11\x11\x22\x22"将产生三个数字0x0000(十进制0),0x1111(十进制4369),0x2222(十进制8738)
我有一个工作解决方案(见下文),但是当我尝试处理服务器发送的数千个数字时,它的功能太慢。请提供一些建议来加快我的方法。
//Works but is too slow!
//$string has the data from the server
$arrayIndex = 0;
for($index = [start of data]; $index < strlen($string); $index+=2){
$value = getNum($string, $index, $index+1);
$array[$arrayIndex++] = $value;
}
function getNum($string, $start, $end){
//get the substring we're interested in transforming
$builder = substr($string, $start, $end-$start+1);
//convert into hex string
$array = unpack("H*data", $builder);
$answer = $array["data"];
//return the value as a number
return hexdec($answer);
}我也试图在一个unpack命令中提取数字,但这不起作用(我在理解要使用的格式字符串时遇到了一些麻烦)
//Not working alternate method
//discard the header (in this case 18 bytes) and put the rest of the
//number values I'm interested in into an array
$unpacked = unpack("c18char/H2*data", $value);
for($i = 0; $i < $size; $i+=1){
$data = $unpacked["data".$i];
$array[$i] = $data;
}