转换十六进制字符串为int [英] Convert hex string to int

查看:105
本文介绍了转换十六进制字符串为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个长度为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

我也试过一次只做两个字符,并将结果乘以转换工作,但数量不对。

  int id = 0; 
for(int h = 0; h {
String sub = hex.subSequence(h,h + 2).toString ();

if(id == 0)
id = Integer.valueOf(sub,16);
else
id * = Integer.valueOf(sub,16);
}
// ID = 8445600其中= 80DEA0如果我将其转换回来。

我不能只使用第三方库,所以必须在Java标准中完成库。

感谢您提前给予的帮助。

解决方案

对于一个int(它是4个字节并签名)它太大了。



使用

  Long.parseLong(AA0F245C,16); 


I am trying to convert a string that is 8 characters long of hex code into an integer so that I can do int comparison instead of string comparisons over a lot of different values.

I know this is fairly trivial in C++ but I need to do it in Java. The test case I need to satisfy is essentially to Convert "AA0F245C" to int and then back to that string so that I know it is converting right.

I have tried the following:

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

I have also tried doing it two characters at a time and multiplying the results, which the conversion works but the number is not right.

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. 

I can not use third party libraries just so you know, so this has to be done in Java standard libraries.

Thank you for your help in advance.

解决方案

It's simply too big for an int (which is 4 bytes and signed).

Use

Long.parseLong("AA0F245C", 16);

这篇关于转换十六进制字符串为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆