SNIPPET 4
Circular Bit Rotation
Rotate bits left or right by `n` positions without losing boundary data.
Silicon Logic
Standard bitwise shift operators (<< and >>) push bits out
of bounds, essentially deleting them.
Circular rotation ensures that bits pushed off one end immediately wrap around
and reappear on the opposite end. We achieve this by combining a standard shift with the
opposite shift for the remaining bits, then ORing them together.
Example 8-bit (val = 129, shift = 1):
val : 10000001 (129)
val << 1 : 00000010 (2)
val >> (8-1) : 00000001 (1)
-------------------
OR (|) : 00000011 (3)
val : 10000001 (129)
val << 1 : 00000010 (2)
val >> (8-1) : 00000001 (1)
-------------------
OR (|) : 00000011 (3)
#include <stdint.h>
// 8-bit ROTL
uint8_t rotate_left(uint8_t val, unsigned int shift) {
shift &= 7; // Ensure bounds (0-7)
if (shift == 0) return val;
uint8_t left_shift = val <<
shift;
uint8_t right_shift = val >>
(8 - shift);
return left_shift | right_shift;
}
int main() {
uint8_t data = 129; // 10000001
uint8_t result = rotate_left(data,
1);
return 0;
}