Search code examples
cbytebit-manipulation

number of bytes required to store a certain number of bits


I have a function that takes as input a number of bits, and returns the number of bytes required to store those bits:

unsigned int get_number_of_bytes(unsigned int number_of_bits);

So, assuming 8 bits per byte:

  • number_of_bits = 0 => function returns 0
  • number_of_bits = 1 => function returns 1
  • number_of_bits = 8 => function returns 1
  • number_of_bits = 9 => function returns 2

A possible implementation would be:

unsigned int get_number_of_bytes(unsigned int number_of_bits)
{
    if (number_of_bits == 0)
        return 0;
    else
        return (number_of_bits - 1) / CHAR_BIT + 1;
}

(CHAR_BIT is usually equal to 8.)

How to code this function without an if (and without a ?: operator)?


Solution

  • unsigned int get_number_of_bytes(unsigned int number_of_bits)
    {
        return (number_of_bits + CHAR_BIT - 1) / CHAR_BIT;
    }