Circular Bit Shifting in PHP
In PHP there is bit shifting to the right and bit shifting to the left, but they just shift bits off of the end of the bytes. At one point in the past for reasons I don't remember I had the need to have the ability to circularly shift bits instead of just shifting them off of a byte. Continue for the explanation and code...
Example:
The binary representation of the letter 'Y' is:
01011001
If you shift that 1 bit to the right then you end up with:
00101100
which is the binary representation of a comma (","). So, if instead of bit shifting one to the right, you circularly bit shifted one bit to the right, you would end up with:
10101100
which is not a displayable character, and has a hex value of 0xAC. Understand the difference?
So I have written a function that does circular bit shifting in PHP. Circular bit shifting on a single byte is relatively easy and nothing special, but this function will also do circular bit shifting on a string of bytes as a whole. So if you passed it the string 'YZ' which has a binary representation of:
01011001 01011010
And told it to shift it 4 bits to the right, then it would return a string with the binary representation of:
10100101 10010101
Here is the function:
function circularBitShift($x, $hm, $direction="r"){ $ret = ''; $hm = ($hm%8); $xhm = 8-$hm; return ''; } for ($i=0; $i<strlen($x); $i++){ } if ($direction=="r"){ foreach ($ords as $i=>$c){ if ($i==0){ $c = $c>>$hm; } else { $orwith = $ords[$i-1]<<$xhm; $c = $c>>$hm; } } } else { foreach ($ords as $i=>$c){ $orwith = $ords[0]>>$xhm; $c = $c<<$hm; } else { $orwith = $ords[$i+1]>>$xhm; $c = $c<<$hm; } } } return $ret; }
The use is circularBitShift(STRING, HOWMANYTOSHIFT, DIRECTION). DIRECTION can be "l" or "r" and HOWMANYTOSHIFT can be anything between 0 and 8 exclusively.
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments
No comments yet.
Leave a comment