this only works for powers of two, due to the sexy nature of how bit masking works - in all other cases - you do this:
x = ((x + (n-1)) / n) * n); // edited
so, to answer the fundamental question here - AWOL was spot on here with the solution, unfortunately since it was low level bitwise C it seems that many have failed to understand what was actually going on.
x = (x + 7) & ~7;
x = ((x + 7) / 8) * 8); // edited
do exactly the same thing.. push x over the 8 boundary (but, only by 7) and then divide ..
the addition of 1 should be conditional something like
I admit I had not thought of that.
But we don't expect division by 0 to work so we check for it before we try the division - same here. perhaps?
Rather than make the formula more complex?
Robin2:
I think it works, but would you care to explain the maths?
we know it works
are you familiar with binary (0's and 1's) and how integers are stored internally?
anyhow, here is the catch - since it is a multiple of a power of 2, we can use the magic trickery of bit wise operations. & ~7 really means - remove the lower three bits from the number (7 = 111 in binary, ~7 = 111111...111111000 in binary) - which really means make them 0. so if you have a number like 181 it is in binary as: 10110101 making the last three bits 0 would make the number: 10110000 which would be the number 176. you can read up more at:
are you familiar with binary (0's and 1's) and how integers are stored internally?
I had figured out the stuff in your post. What I am interested to understand is why it works as maths rather than just as bit manipulations. The bit manipulation stuff is HOW not WHY.