PHP: convert binary to text string


The PHP’s core offers some function to convert data between binary, decimal, hexadecimal and etc. But how to convert from binary to text, we offer some function to do that.

Method 1: using functions pack and base_convert

function binToStr($input)
{
    if (!is_string($input))
        return false;
    return pack('H*', base_convert($input, 2, 16));
}

Example:

echo binToStr('1110100011101010111010001101111'); //tuto

But with the long binary data, we can’t convert

echo binToStr('0111010001110101011101000110111101110010011010010110000101101100011100110111000001101111011101000111001100101110011000110110111101101101'); //tutori`

Because of the function base_convert can’t work with the big number. The limitation is:

echo(PHP_INT_MAX);//2147483647

What’s the sulution? we can split the binary into chunks, convert each chunk to string and join them. We must change the above function:

function binToStr($input)
{
    if (!is_string($input))
        return false;
    $chunks = str_split($input,8);
    $ret = '';
    foreach ($chunks as $chunk)
    {
        $temp = base_convert($chunk, 2, 16);
        $ret .= pack('H*',str_repeat("0", 2 - strlen($temp)) . $temp);
    }
    return $ret;
}

Example:

echo binToStr('0111010001110101011101000110111101110010011010010110000101101100011100110111000001101111011101000111001100101110011000110110111101101101'); //tutorialspots.com

Method 2: use function bindec and chr to convert

function binToStr($input)
{
    if (!is_string($input))
        return false;
    $chunks = str_split($input,8);
    $ret = '';
    foreach ($chunks as $chunk)
    {
        $ret .= chr(bindec($chunk));
    }
    return $ret;
}

Example:

echo binToStr('01110000011010000111000001110100011101010111010001110011'); //phptuts

Read more: PHP: convert string to binary

Related Post

, ,

No comments yet.

Leave a Reply