Reputation: 31
I'm trying to write a byte in binary to a file.
I have the binary byte (8 bits) as a string, e.g. "01100101"
How do I write this as one byte in PHP? When I fopen
with "wb"
it still writes it in ASCII and puts 01100101
in a file. I might be confused how how the whole process works..
Upvotes: 1
Views: 1447
Reputation: 999
file_put_contents('aa',pack('ifA5',1001,25.5,'asdfg'));
var_dump(unpack('iint/ffloat/A5lkl',file_get_contents('aa')));
Upvotes: 0
Reputation: 644
I think pack()
is what you're looking for.
function bin2bstr($input)
// Convert a binary expression (e.g., "100111") into a binary-string
{
if (!is_string($input)) return null; // Sanity check
// Pack into a string
return pack('H*', base_convert($input, 2, 16));
}
Upvotes: 3
Reputation: 109547
$number = bindec("01100101");
$number = 0b01100101; // better
The notation 0b... is for binary numbers.
Upvotes: 0