3v4l.org

run code in 300+ PHP versions simultaneously
<?php function string_shift_left($input, $inputlen, $bits, &$output = null) { $skip = (int) ($bits / 8); $copylen = (int) ($inputlen - $skip); $offset = ($bits % 8) & 0xff; $mask = ~(0xff >> $offset) & 0xff; $output = str_pad('', $inputlen + 1, "\x00"); echo "$skip $copylen $offset $mask\n"; if ($offset == 0) { /* Shifting multiples of 8 allows us to simply copy the relevant bytes */ for ($i = 0; $i < $copylen; $i++) { $output[$i] = $input[$i + $skip]; } return; } for ($i = 0; $i < $copylen; $i++) { $left = (ord($input[$i + $skip]) << $offset) & 0xff; $right = (ord($input[$i + $skip + 1]) & $mask) >> (8 - $offset); printf("%08b %08b\n", $left, $right); $output[$i] = chr(($left | $right) & 0xff); } } function string_shift_right($input, $inputlen, $bits, &$output = null) { $skip = (int) ($bits / 8); $copylen = (int) ($inputlen - $skip); $offsetr = ($bits % 8) & 0xff; $signbits = (ord($input[0]) & 0x80) == 0 ? 0 : 255; echo "$skip $copylen $offsetr $signbits\n"; $output = str_pad('', $inputlen + 1, "\x00"); for ($i = 0; $i < $skip; $i++) { $output[$i] = chr($signbits); } if ($offsetr == 0) { /* Shifting multiples of 8 allows us to simply copy the relevant bytes */ for ($i = $skip, $l = $i + $copylen; $i < $l; $i++) { $output[$i] = $input[$i - $skip]; } return; } $offsetl = 8 - $offsetr; $mask = ~(0xff >> $offsetr) & 0xff; $output[$skip] = chr(($signbits & ~(0xff >> $offsetl)) | (ord($input[0]) >> $offsetl)); /* for ($i = 0; $i < $copylen; $i++) { $left = (ord($input[$i + $skip]) << $offset) & 0xff; $right = (ord($input[$i + $skip + 1]) & $mask) >> (8 - $offset); printf("%08b %08b\n", $left, $right); $output[$i] = chr(($left | $right) & 0xff); } */ } $input = "\xe1bc\x00"; $bits = 4; string_shift_right($input, strlen($input) - 1, $bits, $output); for ($i = 0; $i < strlen($input); $i++) { printf("\n%02x: %08b", ord($input[$i]), ord($input[$i])); } for ($i = 0; $i < strlen($output); $i++) { printf("\n%02x: %08b", ord($output[$i]), ord($output[$i])); }

preferences:
36.73 ms | 402 KiB | 5 Q