Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use CHAR_BIT as the basis for determining the number of bits in other types?

For example, does the following code make no assumptions that might be incorrect on certain systems?

 // Number of bits in an unsigned long long int:
 const int ULLONG_BIT = sizeof(unsigned long long int) * CHAR_BIT;
like image 911
Govind Parmar Avatar asked Nov 24 '25 11:11

Govind Parmar


1 Answers

I agree with PSkocik's comment to the original question. C11 6.2.6 says CHAR_BIT * sizeof (type) yields the number of bits in the object representation of type type, but some of them may be padding bits.

I suspect that your best bet for a "no-assumptions" code is to simply check the value of ULLONG_MAX (or ~0ULL or (unsigned long long)(-1LL), which should all evaluate to the same value):

#include <limits.h>

static inline int ullong_bit(void)
{
    unsigned long long m = ULLONG_MAX;
    int n = 0, i = 0;
    while (m) {
        n += m & 1;
        i ++;
        m >>= 1;
    }
    if (n == i)
        return i;
    else
        return i-1;
}

If the binary pattern for the value is all ones, then the number of bits an unsigned long long can hold is the same as the number of binary digits in the value.

Otherwise, the most significant bit cannot really be used, because the maximum value in binary contains zeros.

like image 93
Nominal Animal Avatar answered Nov 27 '25 01:11

Nominal Animal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!