我试图将一个长度为8个字符的十六进制代码的字符串转换为整数,以便我可以在很多不同的值上进行int比较而不是字符串比较.
我知道这在C++中相当简单,但我需要在Java中完成.我需要满足的测试用例基本上是将"AA0F245C"转换为int然后再返回到该字符串,以便我知道它正在转换.
我尝试过以下方法:
int decode = Integer.decode("0xAA0F245C"); // NumberFormatException
int decode2 = Integer.decode("AA0F245C"); //NumberFormatException
int parseInt = Integer.parseInt("AA0F245C", 16); //NumberFormatException
int valueOf = Integer.valueOf("AA0F245C", 16); //NumberFormatException
Run Code Online (Sandbox Code Playgroud)
我也尝试过一次两个字符并将结果相乘,转换有效,但数字不正确.
int id = 0;
for (int h = 0; h < hex.length(); h= h+2)
{
String sub = hex.subSequence(h, h+2).toString();
if (id == 0)
id = Integer.valueOf(sub, 16);
else
id *= Integer.valueOf(sub, 16);
}
//ID = 8445600 which = 80DEA0 if I convert it back.
Run Code Online (Sandbox Code Playgroud)
我不能只使用第三方库,所以这必须在Java标准库中完成.
提前谢谢你的帮助.