繁体   English   中英

将字符串二进制转换为整数Java

[英]Convert String binary to integer Java

在阅读本书时,我遇到了将二进制转换为整数的情况。 本书给出的代码是:

 // convert a String of 0's and 1's into an integer
    public static int fromBinaryString(String s) {
       int result = 0;
       for (int i = 0; i < s.length(); i++) {
          char c = s.charAt(i);
          if      (c == '0') result = 2 * result;
          else if (c == '1') result = 2 * result + 1;
       }
       return result;
    }

我解决问题的方法是:

public static int fromBinary(String s) {
        int result = 0;
        int powerOfTwo = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if ('1' == s.charAt(i)) {
                result += Math.pow(2, powerOfTwo);
            }
            powerOfTwo++;
        }
 return result;
    }

我知道我的代码有一个额外的计数器,可能有点慢,但是我实现该解决方案的方法是遵循多项式定义

x = xn b ^ n + xn-1 b ^ n-1 + ... + x1 b ^ 1 + x0 b ^ 0。

我不明白他们的解决方案是如何工作的? 我已经调试了,但仍然找不到关键。 有人可以解释吗?

他们基本上将结果移位2 * result ,如果该位置1,则加1。

示例:01101

1. iteration: result = 0 -> result * 2 = 0      (same as binary 00000)
2. iteration: result = 0 -> result * 2 + 1 = 1  (same as binary 00001)
3. iteration: result = 1 -> result * 2 + 1 = 3  (same as binary 00011)  
4. iteration: result = 3 -> result * 2 = 6      (same as binary 00110)
5. iteration: result = 6 -> result * 2 + 1 = 13 (same as binary 01101)

以位为单位:8 + 4 + 1 = 13

或者,您可以将result = result * 2替换为result <<= 1但是在单个语句中添加1则无法使用。 您可以写出result = (result << 1) + 1但是比乘法更长,更难读。

复制多项式定义x = xn b ^ n + xn-1 b ^ n-1 + ... + x1 b ^ 1 + x0 b ^ 0您可以将其重写为

x = ((((...(((( xn * b + xn-1 ) * b + ...  )* b + x1 ) * b + x0 

其中b = 2用于二进制表示,n-1括号在最左侧打开。

对于n = 4,它看起来像

x = ((((x3*2)+x2)*2+x1)*2+x0 = x3 * 2^3 + x2 * 2^2 + x1 * 2^1 + x0 * 2^0

如果您要分析以MSB( x_n )开头的字符串朝向LSB( x_0 )的字符串,则在读取x_i时必须执行

 result = result * 2 + x_i 

在执行此result之前,应该已经存储了值

((...(((( xn * b + xn-1 ) * b + ...  )* b + x_(i+1) )

执行此result后将存储该值

((...(((( xn * b + xn-1 ) * b + ...  )* b + x_i )

通过归纳推理,您可以证明自己最终算出了正确的答案。

暂无
暂无

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

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