繁体   English   中英

无需预制语法将十六进制字符串转换为 integer 值

[英]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 开始
  • 我不知道 316 “幻数”是什么,如果它确实意味着什么,请声明一个具有有意义名称的变量,例如:
final int MEANINGFUL_NAME = 316;

考虑一下,假设您有十六进制值1EC ,十六进制数字为1, E, C 在十进制中,它们将是1, 14, 12

所以设置总和= 0。

  • sum = sum*16 + 1. sum 现在是 1
  • sum = sum*16 + 14 sum 现在是 30
  • sum = sum*16 + 12 sum 现在是 492

所以492就是答案。

如果您有一个1EC字符串,则需要转换为字符,然后将这些字符转换为十六进制值的十进制等效值。

在纸上试一试,直到你有感觉,然后编码。 您可以使用您提到的Integer方法检查您的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM