# Create an array with at least a given number of bits

I use this declaration for an array which must contain a bit for every minute in a day:

UCHAR minutesOfDay[(60 * 24 / CHAR_BIT) + (((60 * 24) % CHAR_BIT) ? 1 : 0)];


However, this look pretty awful. Is there a simpler way to state the same? It can be in C or C++.

• Is CHAR_BIT ever anything other than 8?
– Zack
Apr 13 '16 at 15:51
• @Zack, yes it is. I saw it set to 9 on one particular architecture. Apr 13 '16 at 15:54
• @Zack The TI C55x DSP has 16-bit bytes. Apr 13 '16 at 15:54
• @FelixDombek I assume then that CHAR_BIT is sizeof(UCHAR) then?
– Zack
Apr 13 '16 at 15:57
• @FelixDombek I would go with Bizkit's answer then, put it in a #define, maybe with a comment explaining the math and possible uchar size ramifications. On a semi-related note, I prefer the stdint.h (int16_t, uint8_t, etc) variable type keywords because there is never any confusion about the size (e.g. uint8_t vs UCHAR). Depending on how troublesome the conversion would be, you may want to look into it.
– Zack
Apr 13 '16 at 16:07

Yes, wrap it in a macro:

#ifdef CHAR_BIT
#define BIT_PER_MIN_IN_DAY ((60 * 24 / CHAR_BIT) + (((60 * 24) % CHAR_BIT) ? 1 : 0))
#else
#error "Platform not supported"
#endif

UCHAR minutesOfDay[BIT_PER_MIN_IN_DAY];


Alternate: use integer truncation of division. Add 1 less than the divisor, then divide.

// location of CHAR_BIT
#include <limits.h>

#define MINUTES_PER_DAY (24u * 60)
#define UCHAR_PER_DAY ((MINUTES_PER_DAY + CHAR_BIT - 1)/ CHAR_BIT)
UCHAR minutesOfDay[UCHAR_PER_DAY];


This assumes UCHAR is unsigned char. To avoid that assumption:

#define UCHAR_PER_DAY ((MINUTES_PER_DAY + CHAR_BIT*sizeof(UCHAR) - 1) /  \
(CHAR_BIT*sizeof(UCHAR)))
UCHAR minutesOfDay[UCHAR_PER_DAY];


Pedantically this is not correct had we needed some other unsigned integer type like unsigned or unsigned long. unsigned char, assuming that what UCHAR is, cannot have padding bits. Esoteric platforms could have padding bits with wider unsigned types.