fork download
  1. <?php
  2. $ar = [0, 2, 3, 7, 16, 42];
  3. $maxValue = max( $ar);
  4. if( $maxValue >= pow(2, 32)) {
  5. return; // больше, чем влезет в один ключ в Redis
  6. }
  7. $maxBytes = ceil( $maxValue / 8);
  8. $bin = str_repeat( chr(0x0), $maxBytes);
  9. foreach($ar AS $bitNumber) {
  10. $byteNumber = floor( $bitNumber / 8);
  11. $addon = 1 << ( 7 - $bitNumber % 8);
  12. $byteChar = substr( $bin, $byteNumber, 1);
  13. $byteChar = chr( $addon | ord( $byteChar));
  14. $bin = substr_replace( $bin, $byteChar, $byteNumber, 1);
  15. }
  16. // return $bin;
  17.  
  18. // test output
  19. for( $i=0; $i<strlen($bin); $i++) printf( "%08b ", ord(substr($bin,$i,1)));
  20. echo PHP_EOL;
  21.  
Success #stdin #stdout 0.02s 52432KB
stdin
Standard input is empty
stdout
10110001 00000000 10000000 00000000 00000000 00100000