Simvik

Count the ones

Read off the binary digits of a number one at a time. An easy embedded C problem (Binary and hexadecimal), run and graded in the browser.

easy · Binary and hexadecimal · binary · loops

Dividing by 2 works on binary numbers the way dividing by 10 works on decimal ones. n % 2 is the last binary digit and n / 2 removes it.

Return how many of the binary digits of n are 1. The number 5 is 101 in binary, so the answer is 2.

Starter code

int count_ones(unsigned n) {
  return 0;
}

Example tests

Five is 101

printf("%d\n", count_ones(5));

Expected output:

2

A full byte

printf("%d\n", count_ones(255));

Expected output:

8

Learn it first

  • Binary and hexadecimal · Bits, bytes, hex digits and negative numbers, the way hardware actually stores values.

More Binary and hexadecimal problems