Answer the question
In order to leave comments, you need to log in
How to correctly create a binary string in php?
there is an array $ar = [0, 10, 24522]
how to correctly create a binary string based on it (which will then be transferred to redis).
Each array element sets 1 at the corresponding position in the string.
those. radish will have the following
> getbit keyname 0
(integer) 1
> getbit keyname 10
(integer) 1
> getbit keyname 24522
(integer) 1
(integer) 0
Answer the question
In order to leave comments, you need to log in
I would beat on bytes, and work with bits and individual characters:
$ar = [0, 2, 3, 7, 8];
$maxValue = max( $ar);
if( $maxValue >= pow(2, 32)) {
return; // больше, чем влезет в один ключ в Redis
}
$maxBytes = ceil( $maxValue / 8);
$bin = str_repeat( chr(0x0), $maxBytes);
foreach($ar AS $bitNumber) {
$byteNumber = floor( $bitNumber / 8); // в каком символе строки этот бит окажется
$addon = 1 << ( 7 - $bitNumber % 8); // каков этот бит в своем байте (Redis слева направо)
$byteChar = substr( $bin, $byteNumber, 1); // получаем этот символ из нашей строки
$byteChar = chr( $addon | ord( $byteChar)); // обновляем символ очередным битом
$bin = substr_replace( $bin, $byteChar, $byteNumber, 1); // вставляем обновленный символ в строку
}
// return $bin; // строка готова для Redis'а.
// проверка
for( $i=0; $i<strlen($bin); $i++) printf( "%08b", ord(substr($bin,$i,1)));
echo PHP_EOL;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question