简体   繁体   English

如何在Java中从二进制转换为十进制?

[英]How to convert from binary to decimal in java?

I am trying to write code in java that takes a binary string from the user, then using arrays(?), makes it a base 10 integer. 我试图用从用户处获取二进制字符串的Java编写代码,然后使用arrays(?)使其以10为基数的整数。 My friend trying to help me wrote this, but there is no variable "c" and i do not have any idea what he tried to do. 我的朋友试图帮助我写了这篇文章,但是没有变量“ c”,我也不知道他试图做什么。

 //Binary Conversion
 System.out.println("Enter a value in binary to convert to decimal");
 int binary = 
 int decimalValue = Integer.parseInt(c, 2);

Before this, i already had skeleton code and a declared keyboard scanner, so I assume that 在此之前,我已经有了骨架代码和声明的键盘扫描器,所以我认为

int binary

is followed by 其次是

kbReader.nextInt();

Any help? 有什么帮助吗?

You can read the input as String using scanner.next(); 您可以使用scanner.next()将输入读取为字符串。 then use the Integer parse method as you said which will take the input string and the wanted radix which is in this case =2 然后按照您所说的那样使用Integer parse方法,它将采用输入字符串和所需的基数(在这种情况下= 2)

    **//Conversion between Binary & Decimal**
    public static void main(String args[]){
    **//Binary to Decimal**
            String BtD = "10001110";
            if(isBinary(Integer.parseInt(BtD))){
                System.out.println("Binary Value is ==>> "+Integer.parseInt(BtD));
                System.out.println("Decimal Value is ==>> "+Integer.parseInt(BtD,2));
            }else{
                System.out.println("Not an binary no");
            }
    **//Decimal to Binary**     
            int DtB = 142;
            System.out.println("Decimal Value is ==>> "+DtB);
            System.out.println("Binary Value is ==>> "+Integer.toBinaryString(DtB));
        }
**//To check entered value is binary or not**
        public static boolean isBinary(int number){
            boolean status = true;
            while(true){
                if(number == 0){
                    break;
                }else{
                    int temp = number % 10;
                    if(temp > 1){
                        status = false;
                        break;
                    }
                    number = number /10;
                }
            }
            return status;
        }

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

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