0

我想将下面的 String hex 转换为 Int (16)。

a6 5f de 57

我做了什么,但我不知道这是正确的方法,我无法验证数字是否正确。

byte[] rec = new byte[20];                  
DatagramPacket pRec = new DatagramPacket(rec, rec.length);
socket.receive(pRec);

String tData = "";
for(int i = 0; i < 20; i++){
   tData += String.format("%02x", rec[i]);
}

数据包的输出:

ffffffff730aa65fde5700000000000000000000

现在我必须跳过前 6 个字节 [ffffffff730a],我需要剩下的 4 个字节 [a65fde57]。注意:[00000000000000000000] 是 NULL 因为缓冲区的长度。

System.out.println( hexToInt(tData, 6, 10) );

private Integer hexToInt(String str, int start, int end){
   String t = str.substring(start, end);

   char[] ch = t.toCharArray();
   String res = "";
   for(int i = 0; i < end-start; i += 2){
      res += Integer.parseInt(ch[i]+ch[i+1]+"", 16);
   }

   return Integer.parseInt(res);
}

结果是:

516262

这是将十六进制字符串转换为整数的正确方法吗?结果是否正确?

4

4 回答 4

2

最简单的方法是使用类似 int i = Integer.parseInt(...) 的东西。参见Integer.parseInt(java.lang.String, int)

于 2013-02-16T05:20:56.757 回答
1

我个人会走这条路:

private int hexToInt(String str, int start, int end) {
    String t = str.substring(start, end);

    byte[] bytes = new byte[4];
    int i,j = 0
    while (i < 8)
    {
        bytes[j] = Byte.valueOf(t.substring(i,i+1), 16);
        i+=2; 
        j++;
    }

    ByteBuffer bb = ByteBuffer.wrap(bytes);
    // That's big-endian. If you want little endian ...
    bb.order(ByteOrder.LITTLE_ENDIAN);
    return bb.getInt();
}

您当然可以通过仅传递包含要转换的 8 个字符的子字符串来将其降低一级。

于 2013-02-16T05:35:11.180 回答
1

No, that is not the right way, and that is not the right answer. What you are doing is converting the bytes to values but converting them back to decimal value string, and concatenating those together. Then at the end you convert back to numeric format. Don't convert back and forth so much, convert once to numeric and keep it there. Something like this:

private Integer hexToInt(String str, int start, int end){
    long res = 0;
    for(int i = start; i < end; i++){
        res = res*16  + Integer.parseInt(str.substring(i,i+1), 16);
    }
    return res;
}
于 2013-02-16T08:16:24.280 回答
0
private int convertHexStringToInt(String hexStr)
{
   int iValue= Integer.parseInt(hexStr,16); //base 16 for converting hexadecimal string

   return iValue;
}

请记住,如果十六进制字符串格式以“0x”为前缀,如“0xc38”,那么请从该十六进制字符串中删除 0x。(我建议这样做以避免 NumberFormatException)

您可以使用以下代码来执行此操作

String arrHexStr[] = hexStr.split("x");

if(arrHexStr.length==2)
hexStr = arrHexStr[1]; // this will assign the "c38" value with removed "0x" characters

所以最终的功能看起来像这样

private int convertHexStringToInt(String hexStr)
{
   String arrHexStr[] = hexStr.split("x");

   if(arrHexStr.length==2)
      hexStr = arrHexStr[1]; // this will assign the correct hex string "c38" value with removed prefixes like "0x" 

   int iValue= Integer.parseInt(hexStr,16); //base 16 for converting hexadecimal string

   return iValue;
}
于 2014-05-02T14:15:47.120 回答