doushoubu5360 2012-06-29 18:04
浏览 69
已采纳

PHP:从字符串中提取压缩的十六进制数字

I'm trying to extract packed hexadecimal numbers from a string. My application is communicating with a server which sends a string with a header followed by 2 byte packed hexadecimal numbers. There are thousands of numbers in this string.

What I want to do is extract each 2 byte compressed number, and convert that into a number I can use to perform calculations on.

Example: string = "info:\x00\x00\x11\x11\x22\x22" will produce three numbers 0x0000 (decimal 0), 0x1111 (decimal 4369), 0x2222 (decimal 8738)

I have a working solution (see below,) but it functions too slowly when I try to process the several thousand numbers that the server sends over. Please provide some recommendations to speed up my approach.

//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);
}

I've also been attempting to extract the numbers in a single unpack command, but that is not working (I'm having some trouble understanding the format string to use)

//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;
}
  • 写回答

3条回答 默认 最新

  • doudoulb1234 2012-06-29 18:30
    关注
    $array = array();
    $len = strlen($string);
    for($index = [start of data];          $index < $len;               $index+=2){
        $d = unpack("H*data", substr($string, $index, 2));
        $array[] = hexdec($d["data"]);
    }
    

    The only significant things I did was to cache the value of strlen and reduce function calls.

    you could also try this

    foreach (str_split(substr($string, [start of data]), 2) as $chunk) {
        $d = unpack("H*data", $chunk);
        $array[] = hexdec($d["data"]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100