In PHP, I have some integer variables with values from 0-65535. I need to echo/print it directly, NOT as a printed sequence of characters like printing the string "1281" but the raw binary value. Also I need it so the binary integer sent to the output will always be exactly 2 bytes (zero bytes sent if needed so that it is always 2 bytes). How do I do this in php?
Asked
Active
Viewed 6,562 times
5
-
1The raw binary value is a set of high and low electric voltages inside a circuit. How would you like to represent those voltages in a way humans can perceive? You don't actually NOT want to print out a string representation, you just want to print a different string representation of the number. You are asking to view the number written in base 2 instead of base 10. Both are just string representations of the voltages. – Dan Grossman Dec 12 '10 at 04:23
-
3@Dan, he asked for a raw value, not raw electricity. He never said he didn't want a string, just that he didn't want a string of ASCII digit characters. – Matthew Flaschen Dec 12 '10 at 04:27
-
1@Dan: He basically wants the PHP equivalent of this bit of C: `fwrite(&some_int16_value, sizeof(int16_t), 1, fp)`. At least it reads that way to me. – mu is too short Dec 12 '10 at 04:34
2 Answers
6
To elaborate on mu's answer, you want:
pack("S", $num));
E.g.:
file_put_contents("test65535.bin", pack("S", 65535));
file_put_contents("test100.bin", pack("S", 100));
file_put_contents("test0.bin", pack("S", 0));
hexdump test65535.bin
0000000 ffff
0000002
hexdump test100.bin
0000000 0064
0000002
hexdump test0.bin
0000000 0000
0000002

Matthew Flaschen
- 278,309
- 50
- 514
- 539