Search code examples
javabit-manipulationarithmetic-expressions

How to compute 2^h*ceil(i/2^h)


Is there an easy way to compute:

(2^h)*ceil(i/(2^h))

where i and h are integers, without explicitly using the ceiling function?

For example, for (2^h)*floor(i/(2^h)) can be computed using something like

i&-(1<<h)

which doesn't use the floor function.


Solution

  • Obviously you mean with ^ exponentiation and not bitwise XOR. So something like

    (i + (1 << h) - 1) & (-1 << h)
    

    should work.