Search code examples
javamathpow

Java Bitshift to Replace Math.pow


I need to replace a Math.pow in Java with bitshift.

for (int i = n - 1; i >= 0; i--)
    Math.pow(16, n - i - 1)

Where n is the length of a hex number.
13304fb would mean n= 7.
It's basically converting hex to decimal.

Now I need to replace that Math.pow with Bitshift. I cant figure it out, because the n could be as large as it wants to be.


Solution

    1. 16^(n - i -1) = 2^(4 * (n - i -1))
    2. 2^x = 1 << x.

    Therefore: 16^(n-i-1) = 1 << (4 * (n -i -1))

    (Using the ^ symbol to mean "to the power of", not XOR)