Simvik

Rotate left

Rotate a 32-bit value left by any amount. A medium embedded C problem (Bit manipulation), run and graded in the browser.

medium · Bit manipulation · rotation · undefined-behaviour

Return x rotated left by n bits: bits shifted out of the top re-enter at the bottom.

n can be any value from 0 to 255. Rotating by 32 is the same as rotating by 0, rotating by 36 the same as rotating by 4.

Starter code

uint32_t rotl32(uint32_t x, uint8_t n) {
  // Bits that fall off the top come back in at the bottom.
  return (x << n) | (x >> (32 - n));
}

Example tests

Rotate by one

printf("0x%08X\n", rotl32(0x80000001, 1));

Expected output:

0x00000003

Rotate by a byte

printf("0x%08X\n", rotl32(0x12345678, 8));

Expected output:

0x34567812

Learn it first

  • Bit manipulation · Masks, shifts, fields and the idioms every register access is built from.

More Bit manipulation problems