2012-04-02 99 views
2

我正在嘗試一段代碼。將十六進制數據寫入文件

<?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將被寫入文件。這不會發生。 請幫我解決這個問題。

回答

5

如果要將字節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); 
?> 
+2

+1'chr'更容易,在這裏做這項工作。 'pack'通用性更強,允許以指定的字節順序格式(小端,大端等)轉換多字節值。 – knittl 2012-04-02 09:36:37

+0

非常感謝! :-)我正在嘗試完全相反。 – user1051505 2012-04-02 09:50:59

5

你正在寫的號碼爲0x0F的字符串表示到文件(將每個字符使用1個字節)。

在PHP中你可以使用pack函數來創建二進制字符串。

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