将二进制数转换为十进制数的Java程序。输入是一串零和一串 [英] Java program that converts binary numbers to decimal numbers. The input is a string of zeros and ones

查看:171
本文介绍了将二进制数转换为十进制数的Java程序。输入是一串零和一串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用以下步骤创建一个将二进制转换为十进制的java程序。作为新人我做了一些事情,但我不知道我做错了什么或如何继续。

I have to create a java program that converts binary to decimal using the following steps. 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);
    }
    }

使用循环读取(charAt())每个输入字符串中的数字(0/1字符),从右向左扫描;

Use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left;

使用循环构建所需的2的幂;

Use the loop to build the required powers of 2;

使用条件语句分别处理0和1;

Use a conditional statement to deal with 0 and 1 separately;

使用简单输入进行调试,例如1,10,101,并在循环中打印中间值。

Debug using simple input, e.g. 1, 10, 101, and print intermediate values in the loop.

使用您的程序查找以下二进制数的十进制值:

Use your program to find the decimal value of the following binary number:

1001010101011010111001011101010101010101

1001010101011010111001011101010101010101

推荐答案

仅当您的小数值最多为2147483647或最大值时执行此操作int可以是Java。如果您不知道,只需检查字符串的长度。如果它小于或等于32即4个字节,则可以使用parseInt。:

Do this only if your decimal value is at most 2147483647 or the maximum value an int can be in Java. If you don't know, just check the length of your string. If it's less than or equal to 32 i.e. 4 bytes, then you can use parseInt.:

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

参考这里有关Integer.parseInt()的更多信息;

Refer HERE for more info on the 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);

这篇关于将二进制数转换为十进制数的Java程序。输入是一串零和一串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆