How many bits?
Find the width needed to store a value. An easy embedded C problem (Binary and hexadecimal), run and graded in the browser.
easy · Binary and hexadecimal · binary · ranges
Return the smallest number of binary digits that can hold n. The value 5 is 101, which needs 3 bits. Zero needs 1 bit.
Starter code
int bits_needed(unsigned n) {
return 0;
}Example tests
Five
printf("%d\n", bits_needed(5));Expected output:
3The largest byte value
printf("%d\n", bits_needed(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.
- Count the ones · Read off the binary digits of a number one at a time.
- 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.