繁体   English   中英

Java字符串十六进制为整数

[英]Java string hex to int

我想将下面的String十六进制转换为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

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

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

我个人会走这条路线:

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个字符的子字符串来将其缩小一级。

不,那不是正确的方法,也不是正确的答案。 您要做的是将字节转换为值,但将其转换回十进制值字符串,然后将它们串联在一起。 然后最后将您转换回数字格式。 不要来回转换太多,一次转换为数字并保持不变。 像这样:

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;
}
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;
}

暂无
暂无

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

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