Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a byte array to a hex string in Java?

I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hexcode in the form of: 3a5f771c

like image 535
Andre Avatar asked Mar 11 '12 13:03

Andre


People also ask

How do you convert bytes to hexadecimal?

To convert a byte to hexadecimal equivalent, use the toHexString() method in Java. Firstly, let us take a byte value. byte val1 = (byte)90; Before using the method, let us do some more manipulations.

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 byte to string in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.


1 Answers

From the discussion here, and especially this answer, this is the function I currently use:

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) {     char[] hexChars = new char[bytes.length * 2];     for (int j = 0; j < bytes.length; j++) {         int v = bytes[j] & 0xFF;         hexChars[j * 2] = HEX_ARRAY[v >>> 4];         hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];     }     return new String(hexChars); } 

My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million times) showed it to be much faster than any other alternative, about half the time on long arrays. Compared to the answer I took it from, switching to bitwise ops --- as suggested in the discussion --- cut about 20% off of the time for long arrays. (Edit: When I say it's faster than the alternatives, I mean the alternative code offered in the discussions. Performance is equivalent to Commons Codec, which uses very similar code.)

2k20 version, with respect to Java 9 compact strings:

private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII); public static String bytesToHex(byte[] bytes) {     byte[] hexChars = new byte[bytes.length * 2];     for (int j = 0; j < bytes.length; j++) {         int v = bytes[j] & 0xFF;         hexChars[j * 2] = HEX_ARRAY[v >>> 4];         hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];     }     return new String(hexChars, StandardCharsets.UTF_8); } 
like image 168
maybeWeCouldStealAVan Avatar answered Oct 03 '22 09:10

maybeWeCouldStealAVan