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; $output = str_pad('', $inputlen + 1, "\x00"); for ($i = 0; $i < $skip; $i++) { $output[$i] = $signbits; } if ($offset == 0) { /* Shifting multiples of 8 allows us to simply copy the relevant bytes */ for ($i = $skip; $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); } */ } $input = "abc\x00"; $bits = 32; string_shift_left($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:
33.87 ms | 402 KiB | 5 Q