If pageSize
is a power of two (ie, it has only 1 bit set) then ~(pageSize - 1)
(equivalently to ~pageSize + 1
and to -pageSize
on most systems) still has that specific bit set, and all higher bits also get set:
pageSize = 00001000 // bit k is set
// now the -1 will borrow through all rightmost zeroes and finally reset the 1
pageSize-1 = 00000111 // all bits < k are set
// inverting restores the original 1 and also sets all higher bits
~(pageSize-1)= 11111000 // all bits >= k are set
AND-ing by that aligns to pageSize
, because, for example, being aligned to 8 means that no bits that are "worth less" than 8 are set. The mask leaves 8 (in this example) and all higher powers of two, but all lower powers of two (1, 2 and 4) are removed.