Php 将十六进制数据写入文件

Php 将十六进制数据写入文件,php,Php,我正在尝试一段代码 <?php $tmp = ord('F'); //gives the decimal value of character F (equals 70) $tmp = $tmp - 55; //gives 15 - decimal equivalent of 0x0F $tmp = dechex($tmp); // converts 15 to 0x0F $fp = fopen("testing.data","wb+"); fwrite($fp,$tmp); fclose

我正在尝试一段代码

<?php
$tmp = ord('F'); //gives the decimal value of character F (equals 70)
$tmp = $tmp - 55; //gives 15 - decimal equivalent of 0x0F
$tmp = dechex($tmp); // converts 15 to 0x0F
$fp = fopen("testing.data","wb+");
fwrite($fp,$tmp);
fclose($fp);
?>

当我在十六进制编辑器中打开名为testing.data的文件时,我看到写入了2个字节。这两个字节是0x36和0x33。 我希望只有1个字节(即0x0f)会写入文件。这不会发生。
请帮我解决这个问题。

您正在将数字0x0F的字符串表示形式写入文件(每个字符将使用1个字节)

在PHP中,您将使用该函数创建二进制字符串

$bindata = pack('n', 0x0F);
file_put_contents('testing.data', $bindata);

如果要将字节
0x0f
写入文件,只需使用该ASCII码写入字符即可。实际上,您希望撤消ord,而反向功能是:


+1
chr
更简单,可以在这里完成工作
pack
功能更加广泛,允许使用指定的字节顺序格式(小端、大端等)转换多字节值。非常感谢:-)我试着完全相反。可能是重复的
<?php
$tmp = ord('F'); //gives the decimal value of character F (equals 70)
$tmp = $tmp - 55; //gives 15 - decimal equivalent of 0x0F
$tmp = chr($tmp); // converts 15 to a character
$fp = fopen("testing.data","wb+");
fwrite($fp,$tmp);
fclose($fp);
?>