Rotate a uint32_t left by n bits, so bits that fall off the top come back at the bottom. It must be safe for n = 0 and n ≥ 32.
Solution
main.c
#include <stdint.h>
#include <stdio.h>
uint32_t rotl(uint32_t x, unsigned n) {
n &= 31; /* rotating by 32 = rotating by 0 */
return n ? (x << n) | (x >> (32 - n)) : x; /* avoid the undefined shift by 32 */
}
int main(void) {
printf("0x%08X 0x%08X 0x%08X\n",
(unsigned) rotl(0x12345678u, 8), (unsigned) rotl(0x80000001u, 1), (unsigned) rotl(0xABCDu, 32));
return 0;
}
Output Verified by compiling and running
0x34567812 0x00000003 0x0000ABCD
A rotation is a left shift OR-ed with the bits shifted out on the right. When n is 0, x >> 32 would be undefined, so that case returns x directly. Compilers recognise this pattern and emit a single rotate instruction.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!