LearnFrenzy
Sign in Take a free test

Bitwise Operators · Bit Manipulation Programs · Question 5

Rotate a 32-bit number left in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Popular