3

I want to write a raw byte/byte stream to a position in a file. This is what I have currently:

$fpr = fopen($out, 'r+');
fseek($fpr, 1); //seek to second byte
fwrite($fpr, 0x63); 
fclose($fpr);

This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99.

Thanks for your time.

Yogu
  • 9,165
  • 5
  • 37
  • 58
JP Richardson
  • 38,609
  • 36
  • 119
  • 151

4 Answers4

8

fwrite() takes strings. Try chr(0x63) if you want to write a 0x63 byte to the file.

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
nsayer
  • 16,925
  • 3
  • 33
  • 51
4

That's because fwrite() expects a string as its second argument. Try doing this instead:

fwrite($fpr, chr(0x63));

chr(0x63) returns a string with one character with ASCII value 0x63. (So it'll write the number 0x63 to the file.)

Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
1

You are trying to pass an int to a function that accepts a string, so it's being converted to a string for you.

This will write what you want:

fwrite($fpr, "\x63");
Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
Don Neufeld
  • 22,720
  • 11
  • 51
  • 50
0

If you really want to write binary to files, I would advise to use the pack() approach together with the file API.

See this question for an example.

Community
  • 1
  • 1
Christian
  • 27,509
  • 17
  • 111
  • 155