2
\$\begingroup\$

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

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

2 Answers 2

1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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];
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.