【问题标题】:PHP string to hex/bytes?PHP字符串到十六进制/字节?
【发布时间】:2014-05-26 02:12:51
【问题描述】:

我正在尝试编辑文件的字节。更像是一个十六进制查看器/编辑器。 例如:

//Adding the file bytes to array (byte array)
$bytes = str_split(file_get_contents("test.file")); //It can be any file. like jpg,png, exe, jar...

现在我只想编辑 5 个字节并将它们更改为一些字符值。 例如:

//Adding the file bytes to an array (byte array)
$bytes = str_split(file_get_contents("test.file")); //It can be any file. like jpg,png, exe,jar...

$string = "hello";

$bytes[5] = $string[0];
$bytes[6] = $string[1];
$bytes[7] = $string[3];
$bytes[8] = $string[4];

file_put_contents("edited.file", $bytes);

但它不起作用...我需要先将 $string 的字母转换为字节,然后编辑字节数组的特定字节($bytes),而不会损坏文件。

我曾尝试使用 unpack()、pack() 函数,但我无法使其工作... 我也尝试过 ord() 函数,但随后将它们保存为整数,但我想保存字符串的字节。

【问题讨论】:

标签: php arrays string hex byte


【解决方案1】:

听起来您可能需要使用 unpack 来读取二进制数据,然后进行打包以将其写回。

根据文档,这大致就是您想要的。 (但是 YMMV 因为我从来没有真正为自己做过。)

   <?php
       $binarydata = file_get_contents("test.file");
       $bytes = unpack("s*", $binarydata);
       $string = "hello";
       $bytes[5] = $string[0];
       $bytes[6] = $string[1];
       $bytes[7] = $string[3];
       $bytes[8] = $string[4];
       file_put_contents("edited.file", pack("s*", $bytes));
   ?>

根据注释,unpack 生成的数组从 1 开始,而不是更正常的 0。此外,我不能强调足够强,以至于我根本没有测试过这个建议。充其量将其视为有根据的猜测。

更多信息:http://www.php.net/manual/en/function.unpack.php

更多信息:http://www.php.net/manual/en/function.pack.php

【讨论】:

    猜你喜欢
    • 2015-01-17
    • 2012-01-24
    • 2010-10-04
    • 2020-11-07
    • 2013-08-09
    • 2012-09-25
    • 2013-10-13
    相关资源
    最近更新 更多