简体   繁体   English

将二进制数转换为十进制数的Java程序。 输入是一串零和一串

[英]Java program that converts binary numbers to decimal numbers. The input is a string of zeros and ones

I have to create a java program that converts binary to decimal using the following steps. 我必须创建一个java程序,使用以下步骤将二进制转换为十进制。 Being new at this I did something, but I don't know what I did wrong or how to continue. 作为新人,我做了一些事情,但我不知道我做错了什么或如何继续。

public class BinaryToDecimal {
public static void main(String args[]){
    long sum = 0;
        int result;
        String s = "1001010101011010111001011101010101010101";
        for(int i = s.length()-1; i <= 0; i--){
            result = (int)Math.pow(2, i);
            if(s.charAt(i) == '1')
                sum=sum + result;
        }
        System.out.println(sum);
    }
    }

Use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left; 使用循环读取(charAt())输入字符串中的每个数字(0/1 char),从右向左扫描;

Use the loop to build the required powers of 2; 使用循环来构建所需的2的幂;

Use a conditional statement to deal with 0 and 1 separately; 使用条件语句分别处理0和1;

Debug using simple input, eg 1, 10, 101, and print intermediate values in the loop. 使用简单输入进行调试,例如1,10,101,并在循环中打印中间值。

Use your program to find the decimal value of the following binary number: 使用您的程序查找以下二进制数的十进制值:

1001010101011010111001011101010101010101 1001010101011010111001011101010101010101

Do this only if your decimal value is at most 2147483647 or the maximum value an int can be in Java. 仅当您的十进制值最多为2147483647或者int可以使用Java时的最大值时,才执行此操作。 If you don't know, just check the length of your string. 如果您不知道,只需检查字符串的长度。 If it's less than or equal to 32 ie 4 bytes, then you can use parseInt.: 如果它小于或等于32即4个字节,那么你可以使用parseInt:

int decimalValue = Integer.parseInt(s, 2);

Refer HERE for more info on the Integer.parseInt(); 有关Integer.parseInt()的更多信息,请参阅此处 ;

But if it's more, you can use your code. 但如果它更多,你可以使用你的代码。 I modified your loop which is where your problem was: 我修改了你的问题所在的循环:

 String s = "1001010101011010111001011101010101010101";
 long result = 0;
 for(int i = 0; i < s.length(); i++){
    result = (long) (result + (s.charAt(i)-'0' )* Math.pow(2, s.length()-i-1));
  }
    System.out.println(result);

The loop runs from i = s.length()-1 until i <= 0. This should be i>=0. 循环从i = s.length() - 1开始,直到i <= 0.这应该是i> = 0。
The next problem is "int result". 下一个问题是“int result”。 It works fine with result as a long ;) (Reason: You calculate a 40-bit value at the MostSignificantBit, but Integers only use 32-bit) 它的结果很好;它很长;)(原因:你在MostSignificantBit计算一个40位值,但整数只使用32位)
Also: You start at the rightmost Bit with i=s.length()-1. 另外:你从最右边的位开始,i = s.length() - 1。 But the power that you calculate for it is 2^(s.length()-1) though it should be 2^0=1. 但是你为它计算的功率是2 ^(s.length() - 1),尽管它应该是2 ^ 0 = 1。
The solution is: result = (long)Math.pow(2, s.length()-1-i) 解决方案是:result =(long)Math.pow(2,s.length() - 1-i)

Edit: I really like the solution of user2316981 because of its clear structure (without Math.pow, should be faster by using shift instead). 编辑:我非常喜欢user2316981的解决方案,因为它结构清晰(没有Math.pow,应该通过使用shift来更快)。 And loops from 0 to MSB as I do with Double&Add algorithm. 并且从0到MSB循环,就像我使用Double&Add算法一样。 Can't comment on it yet, but thanks for the reminder ;) 无法评论它,但感谢提醒;)

The first thing I notice is that your binary number has more than 32 bits. 我注意到的第一件事是你的二进制数超过32位。 This cannot be represented in the space of an int, and will result in overflow. 这不能在int的空间中表示,并且会导致溢出。

As a simpler answer, I ran the following and got the correct value at the end, it just uses simple bit shifts. 作为一个更简单的答案,我运行以下内容并在最后得到正确的值,它只使用简单的位移。

For each index in the string, if the character is 1, it sets the corresponding bit in the result. 对于字符串中的每个索引,如果字符为1,则它会在结果中设置相应的位。

public class BinaryToDecimal {
    public static void main(String[] args) {
        long sum;
        String bin = "1001010101011010111001011101010101010101";
        sum = 0;
        for (int i = 0; i < bin.length(); i++) {
            char a = bin.charAt(i);
            if (a == '1') {
               sum |= 0x01;
            }
            sum <<= 1;
        }
        sum >>= 1;
        System.out.println(sum);
    }
 }
import java.util.*;
import java.lang.Math;

class deci {

    int convert(int n) {
        int tem=1,power=0;
        int decimal=0;
        for (int j=0;j<n;j++) {
            if(n==0) {
                break;
            } else {
                while(n>0) {
                    tem=n%10;
                    decimal+=(tem*(Math.pow(2,power)));
                    n=n/10;
                    power++;
                }
            }    
        } 
        return decimal;
    }

    public static void main(String args[]) {
        System.out.print("enter the binary no");
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        deci dc=new deci();
        int i=dc.convert(n);
        System.out.print(i);
    }

}

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

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