Rodrigo
Rodrigo

Reputation: 577

How to convert an array (with TRUE and FALSE values) to binary string to ASCII characters?

I have a list of permissions arranged in an array, for example:

$permissions = array(true, true, false, false, true, ...);

My intention is to convert the array to a chain of 1's and 0's:

$pseudo_binary = array_to_binary($permissions); //011001000110111101100111

And then consider that string as a binary number and stored in the database as an ASCII word:

$ascii = binary_to_word($pseudo_binary); //dog

The array-to-binary() method is not important, I use a simple foreach. But I ask for help to do these conversions:

(string)'011001000110111101100111' -----> 'dog'

'dog' -------> (string)'011001000110111101100111'

Upvotes: 2

Views: 1460

Answers (1)

Rizier123
Rizier123

Reputation: 59681

This should work for you:

First I go through each element with array_map() and replace TRUE -> 1, FALSE -> 0. Then I implode() it into a string.

After this I simply str_split() your string into an array of 8 bits (1 byte). Then I loop through each array element with array_map(), convert the binary to dec with bindec(), and then get the ASCII character of it with chr(). (Also note, that I used sprintf() to make sure each element has 8 bits, otherwise I would fill it up with 0's).

Code:

<?php

    //Equivalent to: 011001000110111101100111
    $permissions = [FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE];

    $binaryPermissionsString = implode("", array_map(function($v){
        return $v == TRUE ? 1 : 0;
    }, $permissions));


    $binaryCharacterArray = str_split($binaryPermissionsString, 8);
    $text = implode("", array_map(function($v){
        return chr(bindec(sprintf("%08d", $v)));
    }, $binaryCharacterArray));

    echo $text;

?>

output:

dog

Upvotes: 2

Related Questions