Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.

suppose I have a string "00A0BF" that I would like interpreted as the

byte[] {0x00,0xA0,0xBf}

what should I do?

I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.

1 Answer

0 votes
by (46k points)

Here's a resolution that I believe is  useful:

public static byte[] hexStringToByteArray(String s) {

    int len = s.length();

    byte[] 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;

}

Ideas why it is an enhancement:

  • Secure with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)
  • Doesn't change the String within a char[], or design StringBuilder and String objects for every single byte.
  • No library dependencies that may not be accessible

Feel loose to add argument checking via assert or exceptions if the argument is not perceived to be reliable.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 13, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...