java.lang.StringIndexOutOfBoundsException

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)

Answers


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

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.


Need Your Help

Equivalent of pthread_mutex_lock and pthread_cond_wait in the linux kernel

c linux-kernel pthreads

What is the equivalent of pthread_mutex_lock and pthread_cond_wait in the linux kernel. and how to use them. Could you please provide simple (hello world) examples.

XmlReader leaving xml file open?

c# xml save

I have an XML file that looks a bit like this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.