简体   繁体   English

在Java中将大二进制字符串转换为十进制

[英]Convert Large Binary String to Decimal in Java

Need a bit of help here: 这里需要一点帮助:

I was assigned a project to convert a Hex values in a file to Decimal using Java without using methods available in Java that can do this directly(we have to do it the long way). 我分配了一个项目,使用Java将文件中的十六进制值转换为Decimal,而不使用Java中可用的直接执行此操作的方法(我们必须做很长的路要走)。

I have converted my Hex values to Binary successfully but am having trouble converting the Binary strings to Decimal. 我已成功将十六进制值转换为Binary,但是将Binary字符串转换为Decimal遇到麻烦。 The output is not correct; 输出不正确; I only need help in this section so I just put the first binary value I need to convert to make things simple to understand and explain. 在本节中我仅需要帮助,因此我只需要输入要转换的第一个二进制值即可使事情易于理解和解释。 Here is what I have so far 这是我到目前为止的

public class binToDec {

    public static void main(String[] args) {
        int decimal = 0;
        String binary = "101010111100110111101111101010111100";
        for (int pow = (binary.length()-1); pow > -1; pow--) {
            if (binary.charAt(pow)=='1'){
            decimal += (Math.pow(2, pow));
            }
        }
        System.out.print(decimal);
    }
}

run: 2147483647 //this is incorrect. 运行:2147483647 //这是不正确的。 it should be 46118402748 应该是46118402748

Thank you so much for your help 非常感谢你的帮助

There are 2 problems with your code. 您的代码有2个问题。

  1. Overflow is certainly occurring, because an int can hold only a value up to 2^31 - 1, and there are more than 31 bits in your binary string. 肯定会发生溢出,因为int最多只能保存2 ^ 31-1的值,并且binary字符串中有超过31位。 Declare decimal to be a long . 声明decimallong

     long decimal = 0; 
  2. You are applying the exponent from the wrong end of your loop when adding to decimal . 当您添加到decimal时,您从循环的错误末端应用了指数。 The 0 char is the most significant, but you are sending in an exponent of 0 , as if it was the least significant. 0字符是最高有效位,但是您要发送的指数为0 ,就好像它是最低有效位一样。 Try 尝试

     decimal += (Math.pow(2, (len - pow - 1))); 

    (This assumes len is declared as int len = binary.length(); .) (这假设len被声明为int len = binary.length();

    Using Math.pow could be considered overkill. 使用Math.pow可能被认为是过大的。 You can also try 您也可以尝试

     decimal += 1L << (len - pow - 1); 

It won't work because int in Java is 32-bit, and your binary string there has 36 bits. 由于Java中的int是32位,而您的二进制字符串只有36位,因此无法正常工作。 This will result in overflow. 这将导致溢出。

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

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