-3

I'm trying to convert a number in the binary system to the decimal system. I have added prints to monitor the variables. When I entered 10 as the number:

the sum before = 0.0

the sum after = 48.0

result of the power = 1

b=0

a=1

.

.

When I enter 101 as the number

sum = 0.0 before

result of the power = 1.0 power

sum = 49.0 after

b = 0

a = 2

.

sum = 49.0before

result of the power = 2.0

sum = 145.0 after

b = 1

a = 1

sum = 145.0

.

sum = 145.0 before

result of the power 4.0

sum = 341.0 after

b = 2

a = 0

sum = 341.0

import java.util.Scanner;

public class Binarium{

    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);
        System.out.println("What is the number?(Only up to ten digits)");
        String number = scan.nextLine();
        System.out.println("What is your conversion");  //d2b b2d 
        String convers = scan.nextLine();
        scan.close();     


    char[] charnumber = number.toCharArray();
    int intnumber = Integer.parseInt(number);
         int a = charnumber.length -1 ;
         double sum1 = 0;
         int b = 0; 
         for (;a>0;a--){
            System.out.println(sum1+"before");
            sum1 = sum1+(charnumber[a]*Math.pow(2, b));
            System.out.println(Math.pow(2, b)+"power");
            System.out.println(sum1+"after");
            System.out.println(b);
            System.out.println(a);
            b= b+1;     
         if(b==4){
             b=0;
         }
         else;

         }System.out.println(sum1);
    }
}

What is the issue with the sums?

4-4
  • 15
  • 3
  • 1
    change `charnumber[a]` to `(charnumber[a]-'0')` – Eran Nov 10 '19 at 14:17
  • `charnumber[a]` gives you the ASCII code of a character, not the number. e.g. `'0' == 48`. Additionally `Math.pow` because it works on flowting point numbers. Use Java shift operator instead: https://stackoverflow.com/a/47893863/150978 – Robert Nov 10 '19 at 14:55

1 Answers1

-1

I solved a challenge the other day that converts from binary to decimal, it's straight forward and might help you:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        //int[] b = {1, 0, 1, 1};

        //using list because the kata is using it: 
        List<Integer> b = new ArrayList();
        b.add(0);
        b.add(0);
        b.add(0);
        b.add(0);
        b.add(1);

        //first thing first i need to remember the formulat: 
        //0101 = 0*2^3 + 1*2^2 + 0*2^1 + 1*2^0 = 0+4+0+1 = 5
        int r = 0; //result
        int hB = b.size() - 1; // high order bit 
        for(int i = 0; i < b.size(); i++)
        {
            r+= b.get(i)* Math.pow(2, hB);

            hB--;
        }
        System.out.println(r);
    }
Apastrix
  • 114
  • 2
  • 12