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 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答