简体   繁体   English

使用java中的数组将二进制转换为十进制

[英]Convert binary to decimal using arrays in java

I'd like to write a program that converts binary to decimal using arrays.我想编写一个使用数组将二进制转换为十进制的程序。 This is the code I have written so far:这是我到目前为止写的代码:

public void BinConvertorDec(){
     int j;
     Scanner in = new Scanner(System.in);
     System.out.println("Enter Binery Index Size: ");
     j = in.nextInt();
     int []ConValue = new int[j]
     System.out.println("Enter a Binary value to convert:");
     for(int i=0; i<ConValue.length; i++){
       ConValue [i] = in.nextInt();
     }
}
    int decimal = 0;
    int power = 0;
    for(int i = 0 ; i < ConValue.length ; i++){
            int tmp = ConValue[i]%10;
            decimal += tmp*Math.pow(2, power);
            power++;
    }
    System.out.println(decimal);

Add that after your for loop.在你的 for 循环之后添加它。 This assumes that the user inputs the string from right to left, changing this should be easy .It works but it would be much easier for your user if they could just input a simple binary string rather than every element of the binary.这假设用户从右到左输入字符串,更改它应该很容易。它可以工作,但如果他们可以输入一个简单的二进制字符串而不是二进制的每个元素,那么对您的用户来说会容易得多。

this is Easy to understand.这很容易理解。

import java.util.*;
class Power{
    int pow(int base , int exponent)
    {
        int result = 1;
        while( exponent != 0)
        {
            result *= base;
            --exponent;
        }
        return result;
    }
}

class Decimal{
    Power obj = new Power(); 
    int dec(int x []){
        int decimal = 0; int exp = 0;
        for( int i = x.length - 1; i > -1; i--){
            decimal += x[i] * obj.pow(2, exp);
            exp++;
        }
    return decimal;
    }

}
class code{
    public static void main(String [] args){
    Decimal DecObj = new Decimal();
    int bin[]= {0,0,1,1,1};
    System.out.println(DecObj.dec(bin));
    }
}

Here is the code convert a number binary to decimal in java.这是在java中将数字二进制转换为十进制的代码。

import java.util.*;
public class HelloWorld {    
static int btod(int n) {
    int count = 0;
    int mul = 1;
    while(n != 0) {
        int dig = n%10;
        count+= dig * mul;
        n /= 10;
        mul *= 2;

    }
    return count;

}

 public static void main(String []args){
     Scanner sc = new Scanner(System.in);
     int n = sc.nextInt();
    System.out.println("Results: " + HelloWorld.btod(n));

 }
}

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

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