如何将数组(具有 TRUE 和 FALSE 值)转换为二进制字符串到 ASCII 字符?
How to convert an array (with TRUE and FALSE values) to binary string to ASCII characters?
我有一个排列成数组的权限列表,例如:
$permissions = array(true, true, false, false, true, ...);
我的目的是将数组转换为 1 和 0 的链:
$pseudo_binary = array_to_binary($permissions); //011001000110111101100111
然后将该字符串视为二进制数并作为 ASCII 字存储在数据库中:
$ascii = binary_to_word($pseudo_binary); //dog
array-to-binary()方法不重要,我用的是简单的foreach。但我请求帮助进行这些转换:
(string)'011001000110111101100111' -----> 'dog'
'dog' -------> (string)'011001000110111101100111'
这应该适合你:
首先,我将 array_map()
and replace TRUE
-> 1
, FALSE
-> 0
. Then I implode()
遍历每个元素并将其转换为字符串。
之后我简单地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()
确保每个元素有8位,否则我会用0填充它)。
代码:
<?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;
?>
输出:
dog
我有一个排列成数组的权限列表,例如:
$permissions = array(true, true, false, false, true, ...);
我的目的是将数组转换为 1 和 0 的链:
$pseudo_binary = array_to_binary($permissions); //011001000110111101100111
然后将该字符串视为二进制数并作为 ASCII 字存储在数据库中:
$ascii = binary_to_word($pseudo_binary); //dog
array-to-binary()方法不重要,我用的是简单的foreach。但我请求帮助进行这些转换:
(string)'011001000110111101100111' -----> 'dog'
'dog' -------> (string)'011001000110111101100111'
这应该适合你:
首先,我将 array_map()
and replace TRUE
-> 1
, FALSE
-> 0
. Then I implode()
遍历每个元素并将其转换为字符串。
之后我简单地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()
确保每个元素有8位,否则我会用0填充它)。
代码:
<?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;
?>
输出:
dog