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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
mdos
Forum Newbie
Posts: 2
Joined: Fri Feb 14, 2003 3:42 pm

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

Post 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
Pance
Forum Newbie
Posts: 2
Joined: Tue Mar 25, 2003 2:51 pm

me tooooooooo

Post 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.
Pance
Forum Newbie
Posts: 2
Joined: Tue Mar 25, 2003 2:51 pm

use chr()

Post 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.
Post Reply