[英]Converting a hexadecimal string to integer value without pre-made syntax
I'm taking a computer organization class in college and I was tasked with writing a java program that takes a user inputted string, calls a function that converts said string into a hexadecimal integer, and then output the results.
踢球者是我不能使用任何現有的語法來做到這一點。 例如,Integer.parseInt(__,16) 或 printf。 這一切都需要硬編碼。
現在我不是要求你為我做功課,只是想朝着正確的方向前進。
到目前為止,我已經做到了,但似乎無法正確創建方法:
import java.util.*;
公共 class Demo_Class {
public static void main(String[] args)
{
Scanner AI = new Scanner(System.in);
String str;
System.out.println("Please input a hexadecimal number: ");
str = AI.nextLine();
converter(str);
}
public static int converter(String in)
{
String New = new String();
for(int i = 0; i<= in.length(); i++)
{
New += in.charAt(i);
System.out.println(New + 316);
}
return 0;
}
}
@WJS 給出了一個很好的提示,我只想補充一點, charAt()
返回以 ASCII 編碼的char 。
正如您在ASCII 表中所見,字符 AF 的十進制值介於 65 到 70 之間,而 0-9 go 則介於 48 到 57 之間,因此您需要使用它們將 ASCII 字符轉換為其預期值。
為此,您可以通過轉換為short
來獲取字符的十進制值,例如short dec = (short)in.charAt(i);
,或直接使用char current = in.charAt(i) - 'A'
之類的字符。
考慮到這一點,剩下的就是一些計算,我會把它作為家庭作業。 :)
還:
i <= in.length()
更改為i < in.length()
,因為它從 0 開始final int MEANINGFUL_NAME = 316;
考慮一下,假設您有十六進制值1EC
,十六進制數字為1, E, C
。 在十進制中,它們將是1, 14, 12
。
所以設置總和= 0。
所以492就是答案。
如果您有一個1EC
字符串,則需要轉換為字符,然后將這些字符轉換為十六進制值的十進制等效值。
在紙上試一試,直到你有感覺,然后編碼。 您可以使用您提到的Integer
方法檢查您的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.