If I was using a loop that looked like this:
String string = "DF3";
for (int i = string.length() - 1; i >= 0; --i) {
int c = string.charAt(i);
convertedHex += (i << 4);
}
How would I calculate Math.pow(16, i)
without using Math.pow()
, another loop, or multiplication? Specifically, how can I do it with only bitwise operators?
You can convert i
-th power of 16 by observing that 16=2 4 , hence 16 i =2 4*i , and that 2 i = 1<<i
. Therefore, 16 i = 1<<i*4
, which can be rewritten as 1<<(i<<2)
to avoid multiplication.
However, you do not need to compute the powers of 16 directly. You can construct the number by repeated multiplication by 16 in the loop, ie
convertedHex = (convertedHex << 4) + nextHexDigit;
Note: int c = string.charAt(i)
gives you the UNICODE code point for the character, not the value of the corresponding digit. Use this code instead:
int nextHexDigit = Character.digit(string.charAt(i), 16);
Given that 1 << i
is same as Math.pow(2, i)
, you can simply use 1 << (i * 4)
. However, note that this is assuming that overflow does not occur for the datatype you are using.
In case of int
, a maximum value of 7 is allowed for i, and in case of long
, a maximum value of 15.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.