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:
2A full byte
printf("%d\n", count_ones(255));Expected output:
8Learn it first
- Binary and hexadecimal · Bits, bytes, hex digits and negative numbers, the way hardware actually stores values.
More Binary and hexadecimal problems
- Value of a bit position · Compute how much each bit of a binary number is worth.
- Largest value in n bits · Work out the range of an unsigned number from its width.
- Value of a hex digit · Convert a hexadecimal character into the number it stands for.
- How many bits? · Find the width needed to store a value.
- Split a byte into hex digits · Find the two hex digits of a byte with division and remainder.
- Read a byte as signed · Interpret the same eight bits as a negative number.