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.

Answer from David L on Stack Overflow
Top answer
1 of 16
797

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.

2 of 16
358

One-liners:

import javax.xml.bind.DatatypeConverter;

public static String toHexString(byte[] array) {
    return DatatypeConverter.printHexBinary(array);
}

public static byte[] toByteArray(String s) {
    return DatatypeConverter.parseHexBinary(s);
}

Warnings:

  • in Java 9 Jigsaw this is no longer part of the (default) java.se root set so it will result in a ClassNotFoundException unless you specify --add-modules java.se.ee (thanks to @eckes)
  • Not available on Android (thanks to Fabian for noting that), but you can just take the source code if your system lacks javax.xml for some reason. Thanks to @Bert Regelink for extracting the source.
🌐
TutorialsPoint
tutorialspoint.com › article › convert-hex-string-to-byte-array-in-java
Convert Hex String to byte Array in Java
Now, take a for loop until the length of the byte array. for (int i = 0; i < val.length; i++) { int index = i * 2; int j = Integer.parseInt(str.substring(index, index + 2), 16); val[i] = (byte) j; } Let us see the complete example. public class Demo { public static void main(String args[]) { String str = "p"; byte[] val = new byte[str.length() / 2]; ...
Discussions

(Java) Questions after converting Hex String to Byte Array
-128 is the decimal from signed 2's complement. I'm thinking you don't want that. You can easily write your own function to do the math as: (80)₁₆ = (8 × 16¹) + (0 × 16⁰) = (128)₁₀ instead of -128 and (8B)₁₆ = (8 × 16¹) + (11 × 16⁰) = (139)₁₀ instead of your value -117. If you have to use the hex to byte array[], then you need to check for out of range values and adjust. Note that the valid range is of byte values is -128 to 127 so you are getting overflow. More on reddit.com
🌐 r/javahelp
5
3
November 20, 2019
(Java) Questions after converting Hex String to Byte Array
What you are seeing is related to two concepts you can Google: two's complement binary representation and Java's use of strictly signed types. The highest (rightmost) bit in any primitive integer type in Java denotes negative numbers. Bytes in Java, instead of being represented as from 0 - 255 are from -128 to 127. Internally, computers and other devices don't care, binary values are what they are. Hex value 80 denotes binary 10000000, so it is the 'first' negative number. More on reddit.com
🌐 r/learnjava
1
8
November 20, 2019
Hex String to Byte array conversion java - Stack Overflow
I know this question is asked a lot of times but please hear me out. Previously I have tried following methods to convert hex string to byte array. say my keyA = "D14E2C5A5B5F", I use byte[] of t... More on stackoverflow.com
🌐 stackoverflow.com
Java: convert a byte array to a hex string? - Stack Overflow
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 More on stackoverflow.com
🌐 stackoverflow.com
People also ask

Can I convert a byte array back to a hex string
ANS: Yes, most methods that convert hex to bytes also provide the reverse operation. For example, HexFormat.of().formatHex(byteArray) or DatatypeConverter.printHexBinary(byteArray).
🌐
sqlpey.com
sqlpey.com › java › java-hex-string-to-byte-array
Java: Convert Hex String to Byte Array Efficiently - sqlpey
What is the most efficient way to convert a hex string to a byte array in modern Java
ANS: For Java 17 and later, java.util.HexFormat.of().parseHex(hexString) is generally considered the most efficient and modern approach due to its optimized implementation.
🌐
sqlpey.com
sqlpey.com › java › java-hex-string-to-byte-array
Java: Convert Hex String to Byte Array Efficiently - sqlpey
Is javax xml bind DatatypeConverter still recommended
ANS: While it works, it’s deprecated and not available by default in newer Java versions (9+). HexFormat (Java 17+) or custom solutions are preferred.
🌐
sqlpey.com
sqlpey.com › java › java-hex-string-to-byte-array
Java: Convert Hex String to Byte Array Efficiently - sqlpey
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-convert-hex-string-to-byte-array
Java Program to Convert Hex String to Byte Array - GeeksforGeeks
July 23, 2025 - Another way to convert a hex string to a byte array is to use the Binary shift operators of Java. Here “<<” bitwise left shift operator is used.
🌐
LearnersBucket
learnersbucket.com › home › examples › java › java program to convert hex string to byte array
Java program to convert Hex String to byte Array - LearnersBucket
April 25, 2023 - private byte[] hexToByte(String str){ byte[] val = new byte[str.length() / 2]; for (int i = 0; i < val.length; i++) { int index = i * 2; int j = Integer.parseInt(str.substring(index, index + 2), 16); val[i] = (byte) j; } return val; } hexToByte("123F92BCD"); // [18, 63, -110, -68] ... Introducing ...
🌐
Reddit
reddit.com › r/javahelp › (java) questions after converting hex string to byte array
r/javahelp on Reddit: (Java) Questions after converting Hex String to Byte Array
November 20, 2019 -

I'm trying to convert the Hex String:

0280000000288B41

etc. 0x02, 0x80, 0x00, .. , 0x8B, 0x41 to byte[] array and send it to a device connected to my laptop.

I'm using 2 ways to convert them. Firstly is this method I found here:

public static byte[] hexStringToByteArray(String hex) {
        int l = hex.length();
        byte[] data = new byte[l/2];
        for (int i = 0; i < l; i += 2) {
            data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i+1), 16));
        }
        return data;
    }

Secondly, it's by using DatatypeConverter

    public static byte[] toByteArray(String s) {
        return DatatypeConverter.parseHexBinary(s);
    }

I have 2 similar results,

index: 0 value: 2
index: 1 value: -128
index: 2 value: 0
index: 3 value: 0
index: 4 value: 0
index: 5 value: 40
index: 6 value: -117
index: 7 value: 65

which is equivalent to:

2, -128, 0, 0, 0, 40, -117, 65

So now, I have a couple of questions. I'm sorry as I'm still learning how to program.

I understand that hexadecimal, decimal, ASCII chars etc are all representations for us programmers, and when I execute my code, it will convert all these representations into binary and send a message to the device attached to my laptop (my communications ports are all okay). I'm supposed to get a response, and although I did, it is not exactly how it turned out to be (the device led out a beeping sound but the display is supposed to show something and it didn't).

I was wondering if there is anything wrong with my code, in terms of sending a message via hexadecimal values?

In addition, why is there a negative sign for the 2nd index? (-128)? does that mean that the hex value of 80 represents -128 in byte (data type)?

Lastly, all these byte values in my byte array are converted automatically in binary (without me doing anything except to run the code for now) to the device, right?

Thank you so much :)

Top answer
1 of 2
1
-128 is the decimal from signed 2's complement. I'm thinking you don't want that. You can easily write your own function to do the math as: (80)₁₆ = (8 × 16¹) + (0 × 16⁰) = (128)₁₀ instead of -128 and (8B)₁₆ = (8 × 16¹) + (11 × 16⁰) = (139)₁₀ instead of your value -117. If you have to use the hex to byte array[], then you need to check for out of range values and adjust. Note that the valid range is of byte values is -128 to 127 so you are getting overflow.
2 of 2
1
I can't tell for DatatypeConverter, though it sure looks fine, but the first way is correct. As for negative values, remember that in Java, all number types but char, represent signed numbers, with positive and negative values. The point of a byte is that it's a thing that has any of 256 possible values. That's usually seen as values 0 to 255, in hexa 00 to FF, but remember that Java's byte type is signed, so it has negative and positive values. To have 256 possibilities it means that the values are -128 to 127. Now, obviously bytes of values 0 to 127 should just be represented with the same Java byte value. It's just when trying to go beyond 127 you overflow the valid range of values, which goes back to the minimum possible value, -128. So with hexa 7F you obtain Jave byte 127, and the next value, hexa 80, obtained by adding 1, adds 1 to byte 127 and therefore gives value -128, thus enabling to cover 256 different values. Similarly, with hex value 00 which gives Java byte 0, if you substract 1 you overflow the range of valid values and roll back to max value FF, which is Java byte -1, substracting 1 to 0.
🌐
Blogger
texnological.blogspot.com › 2014 › 01 › convert-hex-string-to-byte-array-and.html
TeXnological. Technology and Data Science: Convert Hex string to byte array and vice versa using Java
January 8, 2014 - * * @param bytes A Byte array * @return A String representation */ public static String toHexString( byte[] bytes ) { StringBuffer sb = new StringBuffer( bytes.length*2 ); for( int i = 0; i < bytes.length; i++ ) { sb.append( toHex(bytes[i] >> 4) ); sb.append( toHex(bytes[i]) ); } return sb.toString(); } private static char toHex(int nibble) { final char[] hexDigit = { '0','1','2','3','4','5','6','7', '8','9','A','B','C','D','E','F' }; return hexDigit[nibble & 0xF]; } } import javax.xml.bind.DatatypeConverter; public static String toHexString(byte[] array) { return DatatypeConverter.printHexBinary(array); } public static byte[] toByteArray(String s) { return DatatypeConverter.parseHexBinary(s); } Hope help!!
Find elsewhere
🌐
CodingTechRoom
codingtechroom.com › question › convert-hex-string-byte-array-java
How to Convert a Hex String to a Byte Array in Java? - CodingTechRoom
Unlike using BigInteger, which might introduce complexity, we can achieve this using a combination of string manipulation and byte array operations. For a broader Java reference, Java: The Complete Reference, Twelfth Edition is a useful companion. ... 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; } // Usage example: String hexString = "00A0BF"; byte[] byteArray = hexStringToByteArray(hexString); // {0x00, 0xA0, 0xBF}
🌐
sqlpey
sqlpey.com › java › java-hex-string-to-byte-array
Java: Convert Hex String to Byte Array Efficiently - sqlpey
July 22, 2024 - import java.util.HexFormat; public class HexConverter { public static void main(String[] args) { String hexString = "00A0BF"; byte[] byteArray = HexFormat.of().parseHex(hexString); // byteArray will contain {0, -96, -65} System.out.println(java.util.Arrays.toString(byteArray)); } }
🌐
Reddit
reddit.com › r/learnjava › (java) questions after converting hex string to byte array
r/learnjava on Reddit: (Java) Questions after converting Hex String to Byte Array
November 20, 2019 -

I'm trying to convert the Hex String:

0280000000288B41

etc. 0x02, 0x80, 0x00, .. , 0x8B, 0x41 to byte[] array and send it to a device connected to my laptop.

I'm using 2 ways to convert them. Firstly is this method I found here:

public static byte[] hexStringToByteArray(String hex) {
        int l = hex.length();
        byte[] data = new byte[l/2];
        for (int i = 0; i < l; i += 2) {
            data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i+1), 16));
        }
        return data;
    }

Secondly, it's by using DatatypeConverter

    public static byte[] toByteArray(String s) {
        return DatatypeConverter.parseHexBinary(s);
    }

I have 2 similar results,

index: 0 value: 2
index: 1 value: -128
index: 2 value: 0
index: 3 value: 0
index: 4 value: 0
index: 5 value: 40
index: 6 value: -117
index: 7 value: 65

which is equivalent to:

2, -128, 0, 0, 0, 40, -117, 65

So now, I have a couple of questions. I'm sorry as I'm still learning how to program.

I understand that hexadecimal, decimal, ASCII chars etc are all representations for us programmers, and when I execute my code, it will convert all these representations into binary and send a message to the device attached to my laptop (my communications ports are all okay). I'm supposed to get a response, and although I did, it is not exactly how it turned out to be (the device led out a beeping sound but the display is supposed to show something and it didn't).

I was wondering if there is anything wrong with my code, in terms of sending a message via hexadecimal values?

In addition, why is there a negative sign for the 2nd index? (-128)? does that mean that the hex value of 80 represents -128 in byte (data type)?

Lastly, all these byte values in my byte array are converted automatically in binary (without me doing anything except to run the code for now) to the device, right?

Thank you so much :)

🌐
CodingTechRoom
codingtechroom.com › question › convert-hex-string-to-bytes-java
How to Convert a Hexadecimal String to Bytes in Java - CodingTechRoom
... String hexString = "4A656665"; // Example Hexadecimal String byte[] bytes = new byte[hexString.length() / 2]; for (int i = 0; i < bytes.length; i++) { int index = i * 2; int value = Integer.parseInt(hexString.substring(index, index + 2), ...
🌐
Codemia
codemia.io › home › knowledge hub › convert a string representation of a hex dump to a byte array using java?
Convert a string representation of a hex dump to a byte array using Java? | Codemia
January 26, 2025 - The conversion process involves parsing the string to extract two characters at a time, converting these characters into a byte, and then storing the byte in the byte array. Here are the detailed steps: Validate the Input String: Ensure the string is not null, its length is even (since each ...
Top answer
1 of 4
2

The difference is in the leading 0 values created by BigInteger.

public void test() {
    test("D14E2C5A5B5F");
    test("00D14E2C5A5B5F");
    test("614E2C5A5B5F");
    test("00614E2C5A5B5F");
}

private void test(String s) {
    byte[] ka = new BigInteger(s, 16).toByteArray();
    byte[] kb = hexStringToByteArray(s);
    if (!Arrays.equals(ka, kb)) {
        System.out.println(s + ":" + Arrays.toString(ka) + " != " + Arrays.toString(kb));
    }
}

public byte[] hexStringToByteArray(String s) {
    byte[] data = new byte[s.length()/2];
    for (int i = 0; i < data.length; i ++) {
        data[i] = (byte) ((Character.digit(s.charAt(i*2), 16) << 4)
                + Character.digit(s.charAt(i*2 + 1), 16));
    }
    return data;
}

prints

D14E2C5A5B5F:[0, -47, 78, 44, 90, 91, 95] != [-47, 78, 44, 90, 91, 95]

00614E2C5A5B5F:[97, 78, 44, 90, 91, 95] != [0, 97, 78, 44, 90, 91, 95]

See the extra leading 0s.

Also, your hexStringToByteArray is assuming an even number of hex digits - this may be an issue.

Something like this should be correct. It ensure the byte[] is always the right length whatever the length of the string. You may wish to add an exception for when the string is too long.

public byte[] asKey(String hex, int bytes) {
    // Make sure the byte [] is always the correct length.
    byte[] key = new byte[bytes];
    // Using i as the distance from the END of the string.
    for (int i = 0; i < hex.length() && (i / 2) < bytes; i++) {
        // Pull out the hex value of the character.
        int nybble = Character.digit(hex.charAt(hex.length() - 1 - i), 16);
        if ((i & 1) != 0) {
            // When i is odd we shift left 4.
            nybble = nybble << 4;
        }
        // Use OR to avoid sign issues.
        key[bytes - 1 - (i / 2)] |= (byte) nybble;
    }
    return key;
}
2 of 4
0

Try this.

public static byte[] hexStringToByteArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++) {
      int index = i * 2;
      int v = Integer.parseInt(s.substring(index, index + 2), 16);
      b[i] = (byte) v;
    }
    return b;
  }
Top answer
1 of 16
1080

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);
}
2 of 16
545

The Apache Commons Codec library has a Hex class for doing just this type of work.

import org.apache.commons.codec.binary.Hex;

String foo = "I am a string";
byte[] bytes = foo.getBytes();
System.out.println( Hex.encodeHexString( bytes ) );
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › HexFormat.html
HexFormat (Java SE 21 & JDK 21)
January 20, 2026 - Returns the long value parsed from a string range of up to sixteen hexadecimal characters. ... Returns a hashcode for this HexFormat. ... Returns true if the character is a valid hexadecimal character or codepoint. ... Returns true if the hexadecimal digits are uppercase, otherwise false. ... Returns a hexadecimal formatter with no delimiter and lowercase characters. ... Returns a hexadecimal formatter with the delimiter and lowercase characters. ... Returns a byte array containing hexadecimal values parsed from a range of the character array.
🌐
Devgex
devgex.com › en › article › 00005508
Efficient Hex String to Byte Array Conversion in Java - DevGex
November 9, 2025 - Abstract: This article explores various methods to convert a hexadecimal string to a byte array in Java, focusing on a manual parsing approach that is efficient, safe, and compatible across Java versions.
🌐
Baeldung
baeldung.com › home › java › java array › converting between byte arrays and hexadecimal strings in java
Converting Between Byte Arrays and Hexadecimal Strings in Java | Baeldung
March 26, 2025 - First of all, we need to check if the length of the hexadecimal String is an even number. This is because a hexadecimal String with odd length will result in incorrect byte representation. Now, we’ll iterate through the array and convert each hexadecimal pair to a byte: