1

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..

1

3 Answers 3

3

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just commenting here to help me find this later. :-)
0
$number = bindec("01100101");

$number = 0b01100101; // better

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.