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 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?