C
Chris M. Thomasson
How "reliable" is the following code:
____________________________________________________________
#include <stdio.h>
#include <limits.h>
#define COUNT_BITS_X_CALC(mp_value, mp_level) \
(! ((mp_value) >> (CHAR_BIT * (mp_level)))) \
? (CHAR_BIT * (mp_level))
#define COUNT_BITS_X(mp_value) ( \
(COUNT_BITS_X_CALC(mp_value, 1) \
: (COUNT_BITS_X_CALC(mp_value, 2) \
: (COUNT_BITS_X_CALC(mp_value, 4) \
: (COUNT_BITS_X_CALC(mp_value, 5) \
: (COUNT_BITS_X_CALC(mp_value, 6) \
: (COUNT_BITS_X_CALC(mp_value, 7) \
: (COUNT_BITS_X_CALC(mp_value, 8) \
: (COUNT_BITS_X_CALC(mp_value, 9) \
: (COUNT_BITS_X_CALC(mp_value, 10) \
: 0))))))))) \
)
#define COUNT_BITS(mp_value) COUNT_BITS_X(mp_value)
#if (COUNT_BITS(USHRT_MAX) == 16)
typedef short int int16_type;
typedef unsigned short int uint16_type;
#else
# error Platform does not provide an exact 16-bit integer! ;^(...
#endif
int main(void) {
printf(
"char is %lu bits\n"
"short is %lu bits\n"
"int is %lu bits\n"
"long is %lu bits\n"
"int16_type is %lu bits\n",
(unsigned long int)COUNT_BITS(UCHAR_MAX),
(unsigned long int)COUNT_BITS(USHRT_MAX),
(unsigned long int)COUNT_BITS(UINT_MAX),
(unsigned long int)COUNT_BITS(ULONG_MAX),
(unsigned long int)(CHAR_BIT * sizeof(int16_type))
);
return 0;
}
____________________________________________________________
I am tinkering around with different ways to use the pre-processor to
determine exact number of bits in integral types. Is there a much better way
to do this? What am I missing here?
Thanks.
____________________________________________________________
#include <stdio.h>
#include <limits.h>
#define COUNT_BITS_X_CALC(mp_value, mp_level) \
(! ((mp_value) >> (CHAR_BIT * (mp_level)))) \
? (CHAR_BIT * (mp_level))
#define COUNT_BITS_X(mp_value) ( \
(COUNT_BITS_X_CALC(mp_value, 1) \
: (COUNT_BITS_X_CALC(mp_value, 2) \
: (COUNT_BITS_X_CALC(mp_value, 4) \
: (COUNT_BITS_X_CALC(mp_value, 5) \
: (COUNT_BITS_X_CALC(mp_value, 6) \
: (COUNT_BITS_X_CALC(mp_value, 7) \
: (COUNT_BITS_X_CALC(mp_value, 8) \
: (COUNT_BITS_X_CALC(mp_value, 9) \
: (COUNT_BITS_X_CALC(mp_value, 10) \
: 0))))))))) \
)
#define COUNT_BITS(mp_value) COUNT_BITS_X(mp_value)
#if (COUNT_BITS(USHRT_MAX) == 16)
typedef short int int16_type;
typedef unsigned short int uint16_type;
#else
# error Platform does not provide an exact 16-bit integer! ;^(...
#endif
int main(void) {
printf(
"char is %lu bits\n"
"short is %lu bits\n"
"int is %lu bits\n"
"long is %lu bits\n"
"int16_type is %lu bits\n",
(unsigned long int)COUNT_BITS(UCHAR_MAX),
(unsigned long int)COUNT_BITS(USHRT_MAX),
(unsigned long int)COUNT_BITS(UINT_MAX),
(unsigned long int)COUNT_BITS(ULONG_MAX),
(unsigned long int)(CHAR_BIT * sizeof(int16_type))
);
return 0;
}
____________________________________________________________
I am tinkering around with different ways to use the pre-processor to
determine exact number of bits in integral types. Is there a much better way
to do this? What am I missing here?
Thanks.