'Rotating a 4x4 bit matrix counter-clockwise
I found a code snippet that rotates a 4x4 bit matrix 90 degrees right. I'd like to do the same operation and rotate it 90 degrees to the left. I spent some time messing around with the shifts to see if I could get it rotate counter-clockwise but had no luck.
unsigned int rotate_right(unsigned short x)
{
x = (x & 0x0033u) << 2u | (x & 0x00CCu) << 8u | (x & 0xCC00u) >> 2u | (x & 0x3300u) >> 8u;
x = (x & 0x0505u) << 1u | (x & 0x0A0Au) << 4u | (x & 0xA0A0u) >> 1u | (x & 0x5050u) >> 4u;
return x;
}
How would I rotate left using the methods used to rotate right? I know I can rotate 3 times right or maybe rotate once to the right and reverse all the bits... but that feels a bit like cheating. There must be a way to do it in a similar manner as the right rotation.
Here is a godbolt with a couple test scenarios cases. https://godbolt.org/z/1Yecoz594
Solution 1:[1]
You can reverse the operation to get a left rotation. Reverse the two lines and the direction of the bit shifts, but you must also adapt the bit mask, so that it corresponds to the mask after shifting in the clockwise rotation – the source in the clockwise rotation is the target in the anticlockwise rotation and vice versa.
For example this expression in the clockwise rotation:
(x & 0x0033) << 2u
becomes
(x & (0x0033 << 2u)) >> 2u == (x & 0x00CC) >> 2u
The whole function is:
unsigned int rotate_left(unsigned short x)
{
x = (x & 0x0A0A) >> 1u
| (x & 0xA0A0) >> 4u
| (x & 0x5050) << 1u
| (x & 0x0505) << 4u;
x = (x & 0x00CC) >> 2u
| (x & 0xCC00) >> 8u
| (x & 0x3300) << 2u
| (x & 0x0033) << 8u;
return x;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | M Oehm |
