How can I convert a byte array to hexadecimal in Java?

java

Solution

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

Problem

I have an array of bytes. I want each byte String of that array to be converted to its corresponding hexadecimal value. Is there any function in Java to convert a byte array to Hexadecimal?

Original source

Related problems