将十六进制数据写入文件

时间:2012-04-02 09:22:22

标签: 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($fp);
?>

当我在十六进制编辑器中打开名为testing.data的文件时,我看到写入了2个字节。 2个字节是0x36和0x33。 我期待只有1个字节,即0x0f将被写入文件。这不会发生。 请帮帮我。

2 个答案:

答案 0 :(得分:6)

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

在PHP中,您可以使用pack函数创建二进制字符串。

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

答案 1 :(得分:6)

如果要将字节0x0f写入文件,只需使用该ASCII码编写字符即可。您实际上想撤消ord,反向函数是chr

<?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);
?>