0

I am looking for a way to convert string that represents hex values into a byte array. This code is perfect working for even number string length but not for odd number string length. If string length is odd then I get java.lang.StringIndexOutOfBoundsException. Please help.

public byte[] hexStringToByteArray(String s) {
     byte[] data = null;
         if(! s.equals("")){    
            int len = s.length();
            data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                     + Character.digit(s.charAt(i+1), 16));
            }
         }
     return data;
}
1
  • What's wrong with String#getBytes()? Commented May 31, 2019 at 9:38

2 Answers 2

1

Your for loop says to keep looping while i < len which allows i to be the string's last index within your loop, causing s.charAt(i+1) to access a non-existent byte.

Either change the loop condition to i < len-1 or i+1 < len.

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

Comments

0

data in case of odd number becomes of less size.

Suppose string length is 7 then data array would be of size 3,

7/2 = 3 (takes integer value)

Later in the loop you are trying to access data for 0 to 3 (which are 4 size).

Also you are accessing element in s.charAt(i+1) which is resulting larger index as your loop starts with 0 to 7. Value of i changes as :

0 2 4 6

when it is 6 then s.charAt(7) will throw StringIndexOutOfBoundsException. As string is of length 7 (index 0 to 6). 7th index is not present for string.

Solution is to reduce the no. of times loop is running by changing loop condition.

Comments

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.