user1363590
user1363590

Reputation: 31

How to construct and write a byte to a binary file in PHP

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

Answers (3)

javad shariaty
javad shariaty

Reputation: 999

file_put_contents('aa',pack('ifA5',1001,25.5,'asdfg'));
var_dump(unpack('iint/ffloat/A5lkl',file_get_contents('aa')));

Upvotes: 0

Griffin
Griffin

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

Joop Eggen
Joop Eggen

Reputation: 109547

$number = bindec("01100101");

$number = 0b01100101; // better

The notation 0b... is for binary numbers.

Upvotes: 0

Related Questions