2

I have a string containing something like "01001010" and I want to write it into a file using binary. In other words, what's inside that file is not the chars 0/1, but in binary format. How can I make that?

6
  • php.net/manual/en/function.fwrite.php#53622 Commented Nov 3, 2012 at 3:24
  • 1
    You mean you want to convert a string of the form $bitString = '01010101...'; into binary data (0x55...), and then write that to a file? Commented Nov 3, 2012 at 3:39
  • Look into base_convert(), pack() Commented Nov 3, 2012 at 3:42
  • @MarcB but beware that base_convert will fail if you try and handle too many bits at once. Commented Nov 3, 2012 at 3:45
  • @therefromhere: easy enough to yank out (say) 16 chars at a time from the source string and convert them individually. As long as you convert a byte's worth of characters into bits at a time, there's no danger of running into base_convert's limits. Commented Nov 3, 2012 at 3:48

1 Answer 1

2

So you mean you want to convert a string of 0s and 1s (eg $bitString = '01010101...';) into binary data (0x55...), and then write that to a file, you need to do this in two steps.

First, convert your string of zeros and ones into binary - see Converting string of 1s and 0s into binary value, then compress afterwards ,PHP

Note that strings in PHP can store binary data.

Then just write the output to a file, eg using file_put_contents().

Sign up to request clarification or add additional context in comments.

1 Comment

Nice hint anyway. Thanks. Sorry for the late reply since I almost forgot it :)

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.