Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string representation of a hex dump to a byte array using Java?

Tags:

java

hex

byte

dump

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

I couldn't have phrased it better than the person that posted the same question here.

But to keep it original, I'll phrase it my own way: 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.

like image 328
rafraf Avatar asked Sep 26 '08 15:09

rafraf


People also ask

How do you convert a hex string to a byte array?

To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st .

Can we convert string to byte array in Java?

A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes.

What is Hexstring in Java?

Hex String – A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0's and 1's. Eg: “245FC” is a hexadecimal string. Byte Array – A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0.

Is hex a 1 byte?

Now, let's convert a hexadecimal digit to byte. As we know, a byte contains 8 bits. Therefore, we need two hexadecimal digits to create one byte.


1 Answers

Update (2021) - Java 17 now includes java.util.HexFormat (only took 25 years):

HexFormat.of().parseHex(s)


For older versions of Java:

Here's a solution that I think is better than any posted so far:

/* s must be an even-length string. */ 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; } 

Reasons why it is an improvement:

  • Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)

  • Doesn't convert the String into a char[], or create StringBuilder and String objects for every single byte.

  • No library dependencies that may not be available

Feel free to add argument checking via assert or exceptions if the argument is not known to be safe.

like image 83
Dave L. Avatar answered Oct 30 '22 21:10

Dave L.