简体   繁体   中英

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM