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++.

  • \$\begingroup\$ Is CHAR_BIT ever anything other than 8? \$\endgroup\$
    – Zack
    Apr 13 '16 at 15:51
  • \$\begingroup\$ @Zack, yes it is. I saw it set to 9 on one particular architecture. \$\endgroup\$
    – Bizkit
    Apr 13 '16 at 15:54
  • \$\begingroup\$ @Zack The TI C55x DSP has 16-bit bytes. \$\endgroup\$ Apr 13 '16 at 15:54
  • \$\begingroup\$ @FelixDombek I assume then that CHAR_BIT is sizeof(UCHAR) then? \$\endgroup\$
    – Zack
    Apr 13 '16 at 15:57
  • \$\begingroup\$ @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. \$\endgroup\$
    – 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))
    #error "Platform not supported"


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)

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

#define UCHAR_PER_DAY ((MINUTES_PER_DAY + CHAR_BIT*sizeof(UCHAR) - 1) /  \

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.