2

This a code for converting hex to string but it works fine until size of the string doesn't exceeds 62 characters?

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: String index out of range: 62 at java.lang.String.substring(Unknown Source) at HEX.hexToString(HEX.java:36) at HEX.main(HEX.java:56)

3
  • it must be in the input, give us example Commented Sep 7, 2012 at 12:04
  • String hex1 = "234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548d" Commented Sep 7, 2012 at 12:07
  • It's 61 characters and in last iteration of your for cycle you ask for characters 61+62.. That is the problem. What are you actually trying to achieve?? Commented Sep 7, 2012 at 12:08

4 Answers 4

3

i+2 in String str = hex.substring(i, i+2); is the problem. even if i < hex.length(), i+2 is too large if hex.length() is odd.

Sign up to request clarification or add additional context in comments.

Comments

2

You will face this problem only when you have odd number of characters in your string. Fix your function as follows:

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

Comments

0

If youre using String.length in a for loop with i initiated at 0 then you need to -1 from the strings length

for (int i = 0; i < hex.length()-1; i+=2) 

Comments

0

Fix your loop condition :

for (int i = 0; i < hex.length() - 3; i +=2) 

1 Comment

that's too simple. i < hex.length()-3, then i+2 < hex.length()-1, that's not what the OP wants

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.