Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output raw binary integer in php

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?

like image 856
David Chen Avatar asked Dec 12 '10 04:12

David Chen


2 Answers

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
like image 94
Matthew Flaschen Avatar answered Oct 20 '22 10:10

Matthew Flaschen


Yes it is possible, use pack.

like image 24
mu is too short Avatar answered Oct 20 '22 10:10

mu is too short