</>EmbeddedInterview
← All problems · Bit Manipulation

Rotate a 32-bit Register Left

Easy

Rotate x left by n positions, wrapping bits around. Accept any unsigned n. Implement uint32_t rotl(uint32_t x, unsigned n).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Reduce n modulo 32 and handle zero separately.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

uint32_t rotl(uint32_t x, unsigned n)
{
    n %= 32; return n ? (x << n) | (x >> (32-n)) : x;
}

The two shifts combine wrapped and retained bits without shifting by 32.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    
    CHECK(rotl(0x80000000u,1)==1);
    CHECK(rotl(1,32)==1);
    CHECK(rotl(1,33)==2);
    CHECK(rotl(0x12345678u,8)==0x34567812u);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}