basics · intermediate · ~15 min

Rotate left

Circularly shift bits toward the MSB.

Challenge

Implement:

uint32_t rotl32(uint32_t x, int n);

Rotate x left by n positions (bits that fall off the top re-enter at the bottom). n>=0; rotation is mod 32.

Input format

A 32-bit value and a shift n.

Output format

The rotated value.

Constraints

n is reduced mod 32.

Starter code

#include <stdint.h>
/* Rotate x left by n positions (n>=0; rotation is mod 32). */
uint32_t rotl32(uint32_t x,int n){ (void)n; return x; }

Common mistakes

x >> (32-n) is undefined when n==0 (a 32-bit shift). Special-case n%32==0.

Edge cases to handle

n==0 (or a multiple of 32) returns x unchanged.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.