简体   繁体   中英

How to convert char to decimal using an ascii table?

I'm working on a java program to convert a 4 digit binary number to decimal. I need to enter the binary as a String, convert to a char, and then to a decimal. I cannot use something like:

int decimal = Integer.parseInt("1010", 2);

Here is my code so far:

  import java.util.Scanner;

public class BinaryConvert2 {
    public static void main(String[] args){
        System.out.println("Please enter a 4 digit binary number: ");
        Scanner s = new Scanner(System.in);
        String binaryNumber = s.next();
        char a, b, c, d;
        a = binaryNumber.charAt(0);
        a = (char) (a*2*2*2);
        b = binaryNumber.charAt(1);
        b = (char) (b*2*2);
        c = binaryNumber.charAt(2);
        c = (char) (c*2);
        d = binaryNumber.charAt(3);
        d = (char) (d*1);
        System.out.println(binaryNumber + " in decimal is: " + a + b + c + d);
    }
}

I'm trying to multiply the char values by powers of 2 so that it will convert to decimal, but when I run the program, I get weird answers such as :

Please enter a 4 digit binary number: 
1010
1010 in decimal is: ?Àb0

The ascii (char) value of 0 is 48 and the value if 1 is 49,

so you need to subtract 48 from the value

a = binaryNumber.charAt(0);
int aInt = (a - 48) * 2 * 2* 2;
....
System.out.println(binaryNumber + " in decimal is: " + (aInt + bInt + cInt + dInt));

The problem is you are printing the abc and d as chars so it will print what ever decimal value of abc and d correspond to in the ascii table. If you want to print out decimals you will have to convert the value to decimal by subtracting 48 add them together and then print.

Has to be like this: 1010 = 8 + 0 + 2 + 0 = 10 then print 10. You are on the right track

get the numeric value and do multiplication, if you do with char it will use the ASCII value

    int num = 0;
    a = binaryNumber.charAt(0);
    num += (Character.getNumericValue(a) * 2 * 2 * 2);
    b = binaryNumber.charAt(1);
    num += (Character.getNumericValue(b) * 2 * 2);
    c = binaryNumber.charAt(2);
    num += (Character.getNumericValue(c) * 2);
    d = binaryNumber.charAt(3);
    num += (Character.getNumericValue(d) * 1);
    System.out.println(binaryNumber + " in decimal is: " + num);

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