Simvik

Count set bits

Count how many bits of a 32-bit value are 1. An easy embedded C problem (Bit manipulation), run and graded in the browser.

easy · Bit manipulation · popcount

Return the number of 1 bits in x. This is also called the population count or Hamming weight.

Starter code

uint8_t popcount32(uint32_t x) {
  // Return how many bits of x are set.
  return 0;
}

Example tests

One full byte

printf("%u\n", popcount32(0x000000FF));

Expected output:

8

Both ends

printf("%u\n", popcount32(0x80000001));

Expected output:

2

Learn it first

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

More Bit manipulation problems