2

这是将十六进制转换为字符串的代码,但在字符串大小不超过 62 个字符之前它可以正常工作?

public static String hexToString(String hex)
        {       
           StringBuilder output = new StringBuilder();
           for (int i = 0; i < hex.length(); i+=2)
           {
            String str = hex.substring(i, i+2);
            output.append((char)Integer.parseInt(str, 16));
           }
           return(output.toString());
        }

java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:HEX.hexToString(HEX.java:36) 处 HEX.main(HEX.java:56) 处的 java.lang.String.substring(Unknown Source) 处为 62

4

4 回答 4

3

i+2String str = hex.substring(i, i+2);问题所在。即使, 如果是奇数i < hex.length()i+2也太大了。hex.length()

于 2012-09-07T12:04:19.487 回答
2

只有当字符串中有奇数个字符时,您才会遇到这个问题。按如下方式修复您的功能:

public static String hexToString(String hex)
    {       
       StringBuilder output = new StringBuilder();
       String str = "";
       for (int i = 0; i < hex.length(); i+=2)
       {

        if(i+2 < hex.length()){
            str = hex.substring(i, i+2);
        }else{
            str = hex.substring(i, i+1);
        }
        output.append((char)Integer.parseInt(str, 16));
       }
       return(output.toString());
    }
于 2012-09-07T12:28:11.513 回答
0

如果您在 for 循环中使用 String.length 并且 i 从 0 开始,那么您需要从字符串长度中减去 -1

for (int i = 0; i < hex.length()-1; i+=2) 
于 2012-09-07T12:06:29.797 回答
0

修复你的循环条件:

for (int i = 0; i < hex.length() - 3; i +=2) 
于 2012-09-07T12:09:34.533 回答