Skip to content

Instantly share code, notes, and snippets.

@DaveRandom
Created March 20, 2013 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaveRandom/5201273 to your computer and use it in GitHub Desktop.
Save DaveRandom/5201273 to your computer and use it in GitHub Desktop.
Bit-shift PHP strings.
<?php
function str_left_shift($str, $count) {
$bytes = floor($count / 8);
if ($bytes) {
$str = substr($str, $bytes)
. str_repeat("\x00", $bytes);
$count = $count % 8;
}
$flip = 8 - $count;
$base = 0xff << $flip;
$carryLeft = $carryRight = 0;
for ($i = strlen($str) - ++$bytes; $i >= 0; $i--) {
$char = ord($str[$i]);
$carryLeft = ($char & $base) >> $flip;
$str[$i] = chr(($char << $count) | $carryRight);
$carryRight = $carryLeft;
}
return $str;
}
function str_right_shift($str, $count) {
$bytes = floor($count / 8);
if ($bytes) {
$str = str_repeat("\x00", $bytes)
. substr($str, 0, $bytes * -1);
$count = $count % 8;
}
$flip = 8 - $count;
$base = 0xff >> $flip;
$carryLeft = $carryRight = 0;
for ($i = $bytes, $l = strlen($str); $i < $l; $i++) {
$char = ord($str[$i]);
$carryLeft = ($char & $base) << $flip;
$str[$i] = chr(($char >> $count) | $carryRight);
$carryRight = $carryLeft;
}
return $str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment