Page 1 of 1

Using fwrite to write an int (BINARY) to a file

Posted: Fri Feb 14, 2003 3:42 pm
by mdos
If I code up the following:

Code: Select all

$val = 0x4b; // dec 69
$fp = fopen($binfile, "wb");
printf("Writing 0x%x to the file", $val);
fwrite($fp, $val);
This prints out:
Writing 0x4b to the file

Unfortunately, when I open the file, PHP has converted the binary value to an ASCII string representing the decimal value before writing to the file, so the file actually contains two bytes: 0x36 0x39, or "69" if viewed from a text editor.

I have added the optional size arg to fwrite ( fwrite($fp, $val, 1); ), but the file ends up with only 0x36 ("6"), so the string conversion is still taking place.

I don't want this string conversion to take place. I want a single byte (0x4b) in a binary file.
How can I accomplish this?
Thanks in advance.

-Marc

me tooooooooo

Posted: Tue Mar 25, 2003 2:51 pm
by Pance
Me Too. For example I just want to fwrite the hex number 2 but fwrite converts it to the ascii value of 2 which is 50dec or 32 hex.

None of the PHP documentation mentions this.

Did you ever get an answer?

Pance.

use chr()

Posted: Tue Mar 25, 2003 3:33 pm
by Pance
I finaly got it:
for example, if $val=2

fwrite( $handle, chr($val), 1);

will write "02". It will also do this correctly:
if $val=10, will write "0A"

Pance.