SHARE

Tool online: Convert string to binary online

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

Method 1: using functions unpack and base_convert

function strToBin($input)
    {
        if (!is_string($input))
            return false;
        $value = unpack('H*', $input);
        return base_convert($value[1], 16, 2);
    }

Example:

echo(strToBin('tuto')); //1110100011101010111010001101111

but with the long string, we can’t convert

echo(strToBin('tutorialspots.com')); //0000000000000000000000000000000000000000000000000000000000000000

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 hexadecimal string into chunks, convert each chunk and join chunk. We must change the above function:

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

Example:

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

Method 2: use function decbin and ord to convert

function strToBin($input)
{
    if (!is_string($input))
        return false;
    $ret = '';
    for ($i = 0; $i < strlen($input); $i++)
    {
        $temp = decbin(ord($input{$i}));
        $ret .= str_repeat("0", 8 - strlen($temp)) . $temp;
    }
    return $ret;
}

Example:

echo (strToBin('phptuts')); //01110000011010000111000001110100011101010111010001110011

Method 3:

Use GMP module

function string_to_bin($string){
        $a = unpack('C*', $string);
        $c = count($a);
        $ret = gmp_init(0);
        foreach($a as $i=>$num){
            $ret = gmp_add($ret,gmp_mul($num,gmp_pow(256,$c-$i)));
        }
        $ret = gmp_strval($ret,2);
         
        return str_repeat("0", strlen($string)*8 - strlen($ret)) .$ret;
    }