Reputation: 960
I am trying to understand what is happening in this bitwise operation that is used to set the size of a char array but I do not fully understand it.
unsigned long maxParams = 2;// or some other value, I just chose 2 arbitrarily
unsigned char m_uParamBitArray[(((maxParams) + ((8)-1)) & ~((8)-1))/8];
What size is this array set to based on the value of maxParams?
Upvotes: 0
Views: 71
Reputation: 11430
This counts the number of 8-bit chars needed to fit maxParams
bits.
+7
is to round up to the next multiple of 8.
0 -> 7 will round to 0 char
1 -> 8 will round to 1 char
After division by 8. Which is done by /8
The bitwise and is to discard the last three bits before dividing by 8.
Upvotes: 2
Reputation: 726987
When maxParams
is not divisible by eight, the first part of the formula formula rounds it up to the next multiple of eight; otherwise, it leaves the number unchanged. The second part of the formula divides the result by eight, which it can always do without getting a remainder.
In general, if you want to round up to N
without going over it, you can add N-1
before the division:
(x + (N - 1)) / N
You can safely drop the & ~((8)-1)
part of the expression:
(maxParams + (8-1))/8
Upvotes: 2