[英]How to convert char to decimal using an ascii table?
我正在使用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
ascii(字符)值为0
值为48,如果值为1
则值为49,
所以你需要从值中减去48
a = binaryNumber.charAt(0);
int aInt = (a - 48) * 2 * 2* 2;
....
System.out.println(binaryNumber + " in decimal is: " + (aInt + bInt + cInt + dInt));
问题是您将abc和d打印为字符,因此它将打印ASCII表中与abc和d对应的十进制值。 如果要打印出小数,则必须通过减去48将其转换为小数,然后再打印。
必须是这样的:1010 = 8 + 0 + 2 + 0 = 10然后打印10。
获取数值并进行乘法运算,如果对char进行运算,它将使用ASCII值
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.