Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In this example we are going to convert string to binary and binary to string with PHP.


Functions


function strigToBinary($string)
{
$characters = str_split($string);

$binary = [];
foreach ($characters as $character) {
$data = unpack('H*', $character);
$binary[] = base_convert($data[1], 16, 2);
}

return implode(' ', $binary);
}

function binaryToString($binary)
{
$binaries = explode(' ', $binary);

$string = null;
foreach ($binaries as $binary) {
$string .= pack('H*', dechex(bindec($binary)));
}

return $string;
}

Test


$string = 'inanzzz';
echo 'STRING: '.$string.PHP_EOL;
echo 'BINARY: '.$binary = strigToBinary($string).PHP_EOL;
echo 'STRING: '.binaryToString($binary).PHP_EOL;

Result


STRING: inanzzz
BINARY: 1101001 1101110 1100001 1101110 1111010 1111010 1111010
STRING: inanzzz