Question about round_up macro

前端 未结 5 755
暗喜
暗喜 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:36

    The page rounding macros assume that `PAGE_SIZE is a power of two, such as:

    0x0400    -- 1 KiB
    0x0800    -- 2 KiB`
    0x1000    -- 4 KiB
    

    The value of PAGE_SIZE - 1, therefore, is all one bits:

    0x03FF
    0x07FF
    0x0FFF
    

    Therefore, if integers were 16 bits (instead of 32 or 64 - it saves me some typing), then the value of ~(PAGE_SIZE-1) is:

    0xFC00
    0xFE00
    0xF000
    

    When you take the value of x (assuming, implausibly for real life, but sufficient for the purposes of exposition, that ULONG_PTR is an unsigned 16-bit integer) is 0xBFAB, then

    PAGE_SIZE         PAGE_ROUND_DN(0xBFAB)   PAGE_ROUND_UP(0xBFAB)
    
    0x0400     -->    0xBC00                  0xC000
    0x0800     -->    0xB800                  0xC000
    0x1000     -->    0xB000                  0xC000
    

    The macros round down and up to the nearest multiple of a page size. The last five bits would only be zeroed out if PAGE_SIZE == 0x20 (or 32).

提交回复
热议问题