6

How do I convert a string to a binary array in PHP?

4 Answers 4

4

I think you are asking for the equivalent to the Perl pack/unpack functions. If that is the case, I suggest you look at the PHP pack/unpack functions:

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

Comments

2

Let's say that you want to convert $stringA="Hello" to binary.

First take the first character with ord() function. This will give you the ASCII value of the character which is decimal. In this case it is 72.

Now convert it to binary with the dec2bin() function. Then take the next function. You can find how these functions work at http://www.php.net.

OR use this piece of code:

<?php
    // Call the function like this: asc2bin("text to convert");
    function asc2bin($string)
    {
        $result = '';
        $len = strlen($string);
        for ($i = 0; $i < $len; $i++)
        {
            $result .= sprintf("%08b", ord($string{$i}));
        }
        return $result;
    }

    // If you want to test it remove the comments
    //$test=asc2bin("Hello world");
    //echo "Hello world ascii2bin conversion =".$test."<br/>";
    //call the function like this: bin2ascii($variableWhoHoldsTheBinary)
    function bin2ascii($bin)
    {
        $result = '';
        $len = strlen($bin);
        for ($i = 0; $i < $len; $i += 8)
        {
            $result .= chr(bindec(substr($bin, $i, 8)));
        }
        return $result;
    }
    // If you want to test it remove the comments
    //$backAgain=bin2ascii($test);
    //echo "Back again with bin2ascii() =".$backAgain;
?>

Comments

1

If you're trying to access a specific part of a string you can treat it like an array as-is.

$foo = 'bar';
echo $foo[0];

output: b

4 Comments

For this kind of string access, I believe curly brace notation is preferable (otherwise you risk confusing the hell out of anyone else maintaining your code). For example: $foo{0}
Unless I'm mistaken, Curly brace notation for this is deprecated in PHP 6
Ah, here it is: us.php.net/language.types.string The "Note" under the heading - "String access and modification by character"
@EvanK: for any kind of access, I believe square brace notation is preferable (otherwise you risk confusing the hell out of anyone else maintaining your code). For example avoid: $foo{0}
1

There is no such thing as a binary array in PHP. All functions requiring byte streams operate on strings. What is it exactly that you want to do?

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.