简体   繁体   English

仅使用按位运算符计算16的指数

[英]Calculate exponents of 16 using only bitwise operators

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? 如何不使用Math.pow() ,另一个循环或乘法来计算Math.pow(16, i) 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 . 您可以通过观察16 = 2 4 ,从而16 i = 2 4 * i ,以及2 i = 1<<i来转换i的16次幂。 Therefore, 16 i = 1<<i*4 , which can be rewritten as 1<<(i<<2) to avoid multiplication. 因此,16 i = 1<<i*4 ,可以将其重写为1<<(i<<2)以避免乘法。

However, you do not need to compute the powers of 16 directly. 但是,您无需直接计算16的幂。 You can construct the number by repeated multiplication by 16 in the loop, ie 您可以在循环中通过重复乘以16来构造数字,即

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. 注意: int c = string.charAt(i)为您提供字符的UNICODE代码点,而不是相应数字的值。 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) . 鉴于1 << iMath.pow(2, i) ,您可以简单地使用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. int情况下,i的最大值为7;在long情况下,最大值为15。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM