0

Suppose you are using a bit set or something similar, essentially some object that allows you to access the value of individual bits. It may be something simple like an integer word or an array of bytes, or something more generic like a BitSet in Java, depending on the number of bits you want to handle.

My question concerns transforming the length of the useful bits into a length expressed as a number of bytes. This is virtually always required because you typically can't allocate less than 8 bits (1 byte) of memory, and so you end up with extra padding bits in your "bit-set" object.

So, to sum things up, how do you correctly get the size in bytes necessary to accommodate a given size in bits?

NOTE: Take into consideration potential integer overflows that may result in an incorrect answer. For example, n_bytes = (n_bits + 7) / 8 may result in an integer overflow if n_bits is large enough.

2 Answers2

0

Here is an answer that works, however I think there are faster methods than this one.

if ((bit_size % 8) == 0)
    byte_size = bit_size/8
else
    byte_size = bit_size/8 + 1



EDIT: For example, to speed things up, you could replace the division by a right shift and the modulus by a bitwise AND.

if ((bit_size & 7) == 0)
    byte_size = bit_size >> 3
else
    byte_size = (bit_size >> 3) + 1

However, compilers may sometimes make these kinds of optimizations themselves, so this may not be that much better.

0

You can avoid int overflows by using long long ints:

n_bytes = static_cast<int>((n_bits + 7LL) / 8)

Ferruccio
  • 98,941
  • 38
  • 226
  • 299