我正在使用Java程序将4位二进制数转换为十进制。我需要将二进制作为字符串输入,转换为char,然后转换为十进制。我不能使用类似:

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


到目前为止,这是我的代码:

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


我试图将char值乘以2的幂,以便将其转换为十进制,但是当我运行该程序时,我得到了奇怪的答案,例如:

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

最佳答案

0的ascii(字符)值为48,而1的ascii值为49,

因此您需要从值中减去48

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

10-08 14:27