This is a javascript implementation of leftRotate() and rightRotate(), based on the above Answer from Socowi (thank you!)
I needed to emulate a simple compass with 90º degree rotations in both left (counter-clockwise) and right (clockwise) directions (not a real compass, just a funny problem).
So instead of messing up the code by storing the previous orientation and using * if / else * or * switch *, I came up with the idea that a circular-shift or bit-rotation would be much more clean, efficient, and elegant of course.
However, I had the same problem about limiting the mask to 4 bits. Thanks to the above solution I was able to do it! ;)
So assuming the following:
- North = 1 = 0001
- West = 2 = 0010
- South = 4 = 0100
- East = 8 = 1000
When I need to turn 90º from North to -> West I call leftRotate() and so on until I get to the same point again (North).
The same applies in reverse, if turning 90º from North to -> East I call rightRotate(), and then again to turn South, and so on.
Here is the snippet, hope it helps:
const BITS_IN_INTEGER = 4;
const INTEGER_MASK = (1 << BITS_IN_INTEGER) - 1;
// this function rotates to left (counter clockwise) 1,2,4,8...1,2,4,8
function leftRotate(x, n) {
return INTEGER_MASK & ((x << n) | (x >>> (BITS_IN_INTEGER - n)));
}
// this function rotates to right (clockwise) 1,8,4,2...1,8,4,2
function rightRotate(x, n) {
return INTEGER_MASK & ((x << (BITS_IN_INTEGER - n)) | (x >>> n));
}
// Lets rotate:
console.log('--- Rotate to left (counter clockwise) 1,2,4,8...1,2,4,8...1:')
let value = 1;
for (let i = 0; i < 8; i++) {
console.log(value);
value = leftRotate(value, 1);
}
console.log('-- Rotate to right (counter clockwise) 1,8,4,2...1,8,4,2...1:')
for (let i = 0; i < 8; i++) {
console.log(value);
value = rightRotate(value, 1);
}