Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to round up number to an int size boundary number of bytes

The following code rounds up the argument to an int size boundary number of bytes.

  #define _INTSIZE(n) ((sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1))

On my machine int is 4 bytes, so -- correct me if I'm wrong -- this should be the same as looking for the next multiple of 4 of an integer (on my machine). By next multiple of 4, I mean the number should be rounded up to a multiple of 4 if not a multiple of 4. If already a multiple of 4, it should be left alone.

I've been playing around with this code. The long and short of it is: why does this code work? (Maybe it doesn't, but it seems to.) I would like some reason to think it will work for ALL cases, not just the ones I've tried out.

like image 467
user678392 Avatar asked Oct 14 '25 18:10

user678392


1 Answers

The code first adds three to the number.

Then it zeroes out the last two bits to round down to a multiple of fours. Just like you can round down to the nearest multiple of 100 in decimal by replacing the last two digits with zeroes.)

If the number is already a multiple of four, adding three to it and then rounding down to the nearest multiple of four leaves it alone, as desired. If the number is 1, 2, or 3 more than a multiple of 4, adding 3 to it raises it above the next multiple of 4, which it then rounds down to, exactly as desired.

like image 58
David Schwartz Avatar answered Oct 17 '25 10:10

David Schwartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!