user1387866
user1387866

Reputation: 2974

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:

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)?

Upvotes: 1

Views: 1209

Answers (2)

Vexcess
Vexcess

Reputation: 74

The above answer states the answer without showing the thought process to get to it. The formula to find the number of bytes needed to represent n bits is

ceil((float) number_of_bits / (float) BITS_PER_BYTE)

Convert to floating point numbers to preserve precision. Divide the number of bits by the number of bits per byte (8) to get the number of bytes needed. You then ceil the result because you usually can't have a fraction of a byte.

However, to avoid the ceil function use the following formula taken from geeksforgeeks. Because we'd end up casting the result to an integer afterwards anyways, we can just use integer division.

(number_of_bits + BITS_PER_BYTE - 1) / BITS_PER_BYTE

https://www.geeksforgeeks.org/find-ceil-ab-without-using-ceil-function/

Upvotes: 0

John Castleman
John Castleman

Reputation: 1561

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

Upvotes: 3

Related Questions