Next: Range of Type, Up: Data Type Measurements [Contents][Index]
The most common reason that a program needs to know how many bits are in
an integer type is for using an array of long int as a bit vector.
You can access the bit at index n with
vector[n / LONGBITS] & (1 << (n % LONGBITS))
provided you define LONGBITS as the number of bits in a
long int.
There is no operator in the C language that can give you the number of
bits in an integer data type. But you can compute it from the macro
CHAR_BIT, defined in the header file limits.h.
CHAR_BITThis is the number of bits in a char—eight, on most systems.
The value has type int.
You can compute the number of bits in any data type type like this:
sizeof (type) * CHAR_BIT
That expression includes padding bits as well as value and sign bits.
On all systems supported by the GNU C Library, standard integer types other
than _Bool do not have any padding bits. TS 18661-1:2014
defines additional macros for the width of integer types (the number
of value and sign bits); these macros can also be used in #if
preprocessor directives, whereas sizeof cannot. The following
macros are defined in limits.h.
CHAR_WIDTHSCHAR_WIDTHUCHAR_WIDTHSHRT_WIDTHUSHRT_WIDTHINT_WIDTHUINT_WIDTHLONG_WIDTHULONG_WIDTHLLONG_WIDTHULLONG_WIDTHThese are the widths of the types char, signed char,
unsigned char, short int, unsigned short int,
int, unsigned int, long int, unsigned long
int, long long int and unsigned long long int,
respectively.
Further such macros are defined in stdint.h. Apart from those for types specified by width (see Integers), the following are defined.
INTPTR_WIDTHUINTPTR_WIDTHPTRDIFF_WIDTHSIG_ATOMIC_WIDTHSIZE_WIDTHWCHAR_WIDTHWINT_WIDTHThese are the widths of the types intptr_t, uintptr_t,
ptrdiff_t, sig_atomic_t, size_t, wchar_t
and wint_t, respectively.
Next: Range of Type, Up: Data Type Measurements [Contents][Index]