2

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'

2
  • Have you tried something ? Commented Aug 14, 2015 at 22:18
  • What I've found is how to handle a binary number, not a string representing a binary number. Commented Aug 14, 2015 at 22:21

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

question, why do I have to split the string into an array of 8 characters? Can I not run the string as a whole?
@Srini chr() is only for 1 character, so 1 byte for each ASCII character.
Ah, bindec(). First I'm a little embarrassed to know that there was a function for that. But sometimes it is quite difficult to find proper documentation.Thank you very much for your answer, it is perfect.

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.