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);
}
Answer from maybeWeCouldStealAVan on Stack Overflow
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 ) );
🌐
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 - In addition to the methods discussed earlier for converting between byte arrays and hexadecimal strings, Java 17 introduced a convenient alternative through the java.util.HexFormat class.
🌐
Mkyong
mkyong.com › home › java › java – how to convert byte arrays to hex
Java – How to convert byte arrays to Hex | mkyong.com
June 5, 2020 - This String.format is the easiest and obvious way to convert a byte arrays into a hex, x for lower case hex, X upper case hex. ... package com.mkyong.crypto.bytes; import java.nio.charset.StandardCharsets; public class ByteToHexExample1 { ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-convert-byte-array-to-hex-string
Java Program to Convert Byte Array to Hex String - GeeksforGeeks
July 23, 2025 - Here one can also observe that since we deal with numbers and not arbitrary byte strings, this may omit leading zeros in cases. Following is the implementation of the foregoing approach - ... // Java program to convert byte // array to hex string // Approach 4 - Using Hexadecimal Representation // of BigInteger in Java import java.io.*; // Importing the BigInteger class import java.math.BigInteger; public class GFG { public static void toHexString(byte[] byteArray) { // Printing the hexadecimal equivalent as string // representation from the BigInteger class.
🌐
Blogger
javarevisited.blogspot.com › 2013 › 03 › convert-and-print-byte-array-to-hex-string-java-example-tutorial.html
How to Convert and Print Byte array to Hex String in Java? Example
June 25, 2025 - Commons codec provides a utility class Hex, which contains an encodeHexString() method to create Hex String from a byte array. It's one of the best options to generate Hex String if you are already using this library to generate MD5 hash values.
🌐
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 a hexadecimal string formatted from a byte array. Each byte value is formatted as the prefix, two hexadecimal characters selected from uppercase or lowercase digits, and the suffix. A delimiter follows each formatted value, except the last.
🌐
Programiz
programiz.com › java-programming › examples › convert-byte-array-hexadecimal
Java Program to Convert Byte Array to Hexadecimal
public class ByteHex { private final static char[] hexArray = "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] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static void main(String[] args) { byte[] bytes = {10, 2, 15, 11}; String s = bytesToHex(bytes); System.out.println(s); } }
Find elsewhere
🌐
Dev-garden
dev-garden.org › 2013 › 04 › 16 › java-byte-array-as-a-hex-string-the-easy-way
Java Byte Array as a Hex String – The Easy Way | Developer's Garden
Thus, less code in your project for you to test, maintain, checkout, etc. ... import javax.xml.bind.DatatypeConverter; .... //print hex string version of HELLO WORLD byte[] helloBytes = "HELLO WORLD".getBytes(); String helloHex = DatatypeConverter.printHexBinary(helloBytes); System.out.printf("Hello hex: 0x%s\n", helloHex); //convert hex-encoded string back to original string byte[] decodedHex = DatatypeConverter.parseHexBinary(helloHex); String decodedString = new String(decodedHex, "UTF-8"); System.out.printf("Hello decoded : %s\n", decodedString);
🌐
TutorialsPoint
tutorialspoint.com › convert-byte-array-to-hex-string-in-java
How to convert a byte array to a hex string in Java?
January 7, 2025 - The printHexBinary() method of the DatatypeConverter class accepts a byte array and returns a hex string.
🌐
Real's HowTo
rgagnon.com › javadetails › java-0596.html
Convert a byte array to a Hex string - Real's Java How-to
static final String HEXES = "0123456789ABCDEF"; public static String getHex( byte [] raw ) { if ( raw == null ) { return null; } final StringBuilder hex = new StringBuilder( 2 * raw.length ); for ( final byte b : raw ) { hex.append(HEXES.charAt((b ...
🌐
Favr
favr.dev › patrick's portfolio website › articles › q java convert a byte array to a hex string?
Q: Java: convert a byte array to a hex string? · favr.dev | Portfolio
February 26, 2023 - Using the %X placeholder, String.format() is able to encode most primitive types (short, int, long) to hex: String.format("%X", ByteBuffer.wrap(eightByteArray).getLong()); If you exclusively have 4 bytes arrays you can use the toHexString method of the Integer class: Integer.toHexString(By...
Top answer
1 of 16
361
byte[] bytes = {-1, 0, 1, 2, 3 };
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
    sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
// prints "FF 00 01 02 03 "

See also

  • java.util.Formatter syntax
    • %[flags][width]conversion
      • Flag '0' - The result will be zero-padded
      • Width 2
      • Conversion 'X' - The result is formatted as a hexadecimal integer, uppercase

Looking at the text of the question, it's also possible that this is what is requested:

String[] arr = {"-1", "0", "10", "20" };
for (int i = 0; i < arr.length; i++) {
    arr[i] = String.format("%02x", Byte.parseByte(arr[i]));
}
System.out.println(java.util.Arrays.toString(arr));
// prints "[ff, 00, 0a, 14]"

Several answers here uses Integer.toHexString(int); this is doable, but with some caveats. Since the parameter is an int, a widening primitive conversion is performed to the byte argument, which involves sign extension.

byte b = -1;
System.out.println(Integer.toHexString(b));
// prints "ffffffff"

The 8-bit byte, which is signed in Java, is sign-extended to a 32-bit int. To effectively undo this sign extension, one can mask the byte with 0xFF.

byte b = -1;
System.out.println(Integer.toHexString(b & 0xFF));
// prints "ff"

Another issue with using toHexString is that it doesn't pad with zeroes:

byte b = 10;
System.out.println(Integer.toHexString(b & 0xFF));
// prints "a"

Both factors combined should make the String.format solution more preferable.

References

  • JLS 4.2.1 Integral Types and Values
    • For byte, from -128 to 127, inclusive
  • JLS 5.1.2 Widening Primitive Conversion
2 of 16
79

I am posting because none of the existing answers explain why their approaches work, which I think is really important for this problem. In some cases, this causes the proposed solution to appear unnecessarily complicated and subtle. To illustrate I will provide a fairly straightforward approach, but I'll provide a bit more detail to help illustrate why it works.

First off, what are we trying to do? We want to convert a byte value (or an array of bytes) to a string which represents a hexadecimal value in ASCII. So step one is to find out exactly what a byte in Java is:

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

What does this mean? A few things: First and most importantly, it means we are working with 8-bits. So for example we can write the number 2 as 0000 0010. However, since it is two's complement, we write a negative 2 like this: 1111 1110. What is also means is that converting to hex is very straightforward. That is, you simply convert each 4 bit segment directly to hex. Note that to make sense of negative numbers in this scheme you will first need to understand two's complement. If you don't already understand two's complement, you can read an excellent explanation, here: http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html


Converting Two's Complement to Hex In General

Once a number is in two's complement it is dead simple to convert it to hex. In general, converting from binary to hex is very straightforward, and as you will see in the next two examples, you can go directly from two's complement to hex.

Examples

Example 1: Convert 2 to Hex.

1) First convert 2 to binary in two's complement:

2 (base 10) = 0000 0010 (base 2)

2) Now convert binary to hex:

0000 = 0x0 in hex
0010 = 0x2 in hex

therefore 2 = 0000 0010 = 0x02. 

Example 2: Convert -2 (in two's complement) to Hex.

1) First convert -2 to binary in two's complement:

-2 (base 10) = 0000 0010 (direct conversion to binary) 
               1111 1101 (invert bits)
               1111 1110 (add 1)
therefore: -2 = 1111 1110 (in two's complement)

2) Now Convert to Hex:

1111 = 0xF in hex
1110 = 0xE in hex

therefore: -2 = 1111 1110 = 0xFE.


Doing this In Java

Now that we've covered the concept, you'll find we can achieve what we want with some simple masking and shifting. The key thing to understand is that the byte you are trying to convert is already in two's complement. You don't do this conversion yourself. I think this is a major point of confusion on this issue. Take for example the follow byte array:

byte[] bytes = new byte[]{-2,2};

We just manually converted them to hex, above, but how can we do it in Java? Here's how:

Step 1: Create a StringBuffer to hold our computation.

StringBuffer buffer = new StringBuffer();

Step 2: Isolate the higher order bits, convert them to hex, and append them to the buffer

Given the binary number 1111 1110, we can isolate the higher order bits by first shifting them over by 4, and then zeroing out the rest of the number. Logically this is simple, however, the implementation details in Java (and many languages) introduce a wrinkle because of sign extension. Essentially, when you shift a byte value, Java first converts your value to an integer, and then performs sign extension. So while you would expect 1111 1110 >> 4 to be 0000 1111, in reality, in Java it is represented as the two's complement 0xFFFFFFFF!

So returning to our example:

1111 1110 >> 4 (shift right 4) = 1111 1111 1111 1111 1111 1111 1111 1111 (32 bit sign-extended number in two's complement)

We can then isolate the bits with a mask:

1111 1111 1111 1111 1111 1111 1111 1111 & 0xF = 0000 0000 0000 0000 0000 0000 0000 1111
therefore: 1111 = 0xF in hex. 

In Java we can do this all in one shot:

Character.forDigit((bytes[0] >> 4) & 0xF, 16);

The forDigit function just maps the number you pass it onto the set of hexadecimal numbers 0-F.

Step 3: Next we need to isolate the lower order bits. Since the bits we want are already in the correct position, we can just mask them out:

1111 1110 & 0xF = 0000 0000 0000 0000 0000 0000 0000 1110 (recall sign extension from before)
therefore: 1110 = 0xE in hex.  

Like before, in Java we can do this all in one shot:

Character.forDigit((bytes[0] & 0xF), 16);

Putting this all together we can do it as a for loop and convert the entire array:

for(int i=0; i < bytes.length; i++){
    buffer.append(Character.forDigit((bytes[i] >> 4) & 0xF, 16));
    buffer.append(Character.forDigit((bytes[i] & 0xF), 16));
}

Hopefully this explanation makes things clearer for those of you wondering exactly what is going on in the many examples you will find on the internet. Hopefully I didn't make any egregious errors, but suggestions and corrections are highly welcome!

🌐
Codemia
codemia.io › home › knowledge hub › java convert a byte array to a hex string?
Java convert a byte array to a hex string? | Codemia
January 9, 2025 - Converting a byte array to a hexadecimal string is a common operation in Java programming, especially in fields dealing with encryption, compression, or network transmission.
🌐
Mkyong
mkyong.com › home › java › how to convert string to hex in java
How to convert String to Hex in Java - Mkyong.com
February 28, 2020 - package com.mkyong; import java.nio.charset.StandardCharsets; public class HexUtils3 { private static final char[] HEX_UPPER = "0123456789ABCDEF".toCharArray(); private static final char[] HEX_LOWER = "0123456789abcdef".toCharArray(); public static void main(String[] args) { String input = "java"; System.out.println("input : " + input); String hex = convertStringToHex(input, false); System.out.println("hex : " + hex); } public static String convertStringToHex(String str, boolean lowercase) { char[] HEX_ARRAY = lowercase ? HEX_LOWER : HEX_UPPER; byte[] bytes = str.getBytes(StandardCharsets.UTF_8); // two chars form the hex value.
🌐
GitHub
gist.github.com › 956fc5ad093323a3b5e6ab696841dc6c
java byte array to hex string · GitHub
from https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java
🌐
Vultr Docs
docs.vultr.com › java › examples › convert byte array to hexadecimal
Java Program to Convert Byte Array to Hexadecimal
December 16, 2024 - The method bytesToHex takes a byte array and converts each byte to its hexadecimal string representation. The bitwise "AND" operation with 0xFF preserves the byte's value as an integer.
🌐
The Coding Forums
thecodingforums.com › archive › archive › java
convert byte array to hex string using BigInteger | Java | Coding Forums
June 20, 2013 - It should be quite a bit faster than using high level routines. /** * Fast convert a byte array to a hex string * with possible leading zero. * @param b array of bytes to convert to string * @return hex representation, two chars per byte.