douchongbc72264 2012-12-23 19:48
浏览 300

在PHP中用Hex字符串写二进制数据

I'm trying to write a binary file from hex string. For example, if my hex string is C27EF0EC, then the hex file should contain ASCII characters for C2, 7E, F0 and EC.
How do I do this in PHP?

Here's what I've tried:

$s="";
for ($i=0; $i<count($h); $i++) {
    $s+=pack("C*", "0x".$h[$i]);
}
$f2=fopen("codes0", "wb+");
fwrite($f2, $s);
  • 写回答

2条回答 默认 最新

  • duanhuan5409 2012-12-23 20:08
    关注

    So the first thing you need to do is turn your single string into an array of two-character strings with str_split.

    $hex_bytes = str_split($h, 2);
    

    Then you want to convert each of those values from a hexadecimal string to the corresponding number with hexdec.

    $code_array = array_map(hexdec, $hex_bytes);
    

    Then you want the byte value corresponding to each of those character codes, which you can get with chr:

    $char_array = array_map(chr, $code_array);
    

    Finally, you want to join all those bytes together into a single string, which you can do with implode.

    $s = implode($char_array);
    

    You can use the steps above in that order, or you can put it all together into one expression like this:

    $s = implode(array_map(chr, array_map(hexdec, str_split($h,2))));
    

    Note that as soon as you get a value above 0x7F it's no longer "ASCII".

    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试