4

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user678392
  • 1,981
  • 3
  • 28
  • 50

2 Answers2

10

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
3

There is actually a subtle bug in this. the '& ~(sizeof(int) - 1)' only works if sizeof(int) is a power of two, 36 bit and 80 bit architectures among others do exist. if you change it to '% sizeof(int)' then it will always be correct.

John Meacham
  • 785
  • 7
  • 9