can anyone please explain how this works (asz + 7) & ~7; It rounds off asz to the next higher multiple of 8.
It is easy to see that ~7 produces 11111000 (8bit repre
The +7 isn't to produce an exact multiple of 8, it's to make sure you get the next highest multiple of eight.
edit: Beaten by 16 seconds and several orders of quality. Oh well, back to lurking.
Uhh, you just answered your own question??? by adding 7, you are guaranteeing the result will be at or above the next multiple of 8. truncating then gives you that multiple.
Without the +7 it will be the biggest multiple of 8 less or equal to your orig number
Well, if you were trying to round down, you wouldn't need the addition. Just doing the masking step would clear out the bottom bits and you'd get rounded to the next lower multiple.
If you want to round up, first you have to add enough to "get past" the next multiple of 8. Then the same masking step takes you back down to the multiple of 8. The reason you choose 7 is that it's the only number guaranteed to be "big enough" to get you from any number up past the next multiple of 8 without going up an extra multiple if your original number were already a multiple of 8.
In general, to round up to a power of two:
unsigned int roundTo(unsigned int value, unsigned int roundTo)
{
return (value + (roundTo - 1)) & ~(roundTo - 1);
}
It's actually adding 7 to the number and rounding down.
This has the desired effect of rounding up to the next multiple of 8. (Adding +8 instead of +7 would bump a value of 8 to 16.)
Well, the mask would produce an exact multiple of 8 by itself. Adding 7 to asz ensures that you get the next higher multiple.