简体   繁体   中英

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. 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.

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));

 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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