[英]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.