我正在尝试将一个8个字符长度的十六进制代码的字符串转换为一个整数,这样我就可以进行int比较,而不是对许多不同的值进行字符串比较。
我知道这在C++中是相当微不足道的,但我需要用Java语言来做。我需要满足的测试用例基本上是将"AA0F245C“转换为整数,然后再转换回该字符串,这样我就知道它是正确转换的。
我尝试过以下几种方法:
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
我也尝试过一次使用两个字符,并将结果相乘,结果转换正常,但数字不正确。
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.
我不能使用第三方库,所以这必须在Java标准库中完成。
提前感谢您的帮助。
https://stackoverflow.com/questions/11194513
复制相似问题