Question about round_up macro

前端 未结 5 831
暗喜
暗喜 2021-02-07 12:55
#define ROUND_UP(N, S) ((((N) + (S) - 1) / (S)) * (S))

With the above macro, could someone please help me on understanding the \"(s)-1\" part, why\'s t

5条回答
  •  眼角桃花
    2021-02-07 13:46

    Using integer arithmetic, dividing always rounds down. To fix that, you add the largest possible number that won't affect the result if the original number was evenly divisible. For the number S, that largest possible number is S-1.

    Rounding to a power of 2 is special, because you can do it with bit operations. A multiple of 2 will aways have a zero in the bottom bit, a multiple of 4 will always have zero in the bottom two bits, etc. The binary representation of a power of 2 is a single bit followed by a bunch of zeros; subtracting 1 will clear that bit, and set all the bits to the right. Inverting that value creates a bit mask with zeros in the places that need to be cleared. The & operator will clear those bits in your value, thus rounding the value down. The same trick of adding (PAGE_SIZE-1) to the original value causes it to round up instead of down.

提交回复
热议问题