Home >Java >javaTutorial >How to Convert a Byte Array to Hexadecimal in Java?
Convert Byte Array to Hexadecimal in Java
Convert a byte array to its hexadecimal representation is a common task in software development. Java provides several methods to achieve this conversion.
One approach involves utilizing the String.format() method with a specific format string: "X". Here's an example:
byte[] bytes = {-1, 0, 1, 2, 3 }; StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X ", b)); // Pad with zero and separate with space } System.out.println(sb.toString()); // Prints "FF 00 01 02 03"
This method ensures that each byte is represented as a two-character hexadecimal string, with leading zeros to fill any vacant positions.
Alternatively, for a more compact representation, you can omit the padding and separator:
StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%X", b)); // Shorter representation } System.out.println(sb.toString()); // Prints "FF00010203"
It's worth noting that converting a signed byte to a 32-bit integer before converting to hexadecimal using Integer.toHexString() may lead to incorrect results due to sign extension. To avoid this issue, you can explicitly mask the byte value with 0xFF:
byte b = -1; System.out.println(Integer.toHexString(b & 0xFF)); // Correct conversion: "FF"
Finally, if your byte array contains ASCII characters rather than raw bytes, you can use the new String(bytes, "US-ASCII") constructor to create a string representation directly.
The above is the detailed content of How to Convert a Byte Array to Hexadecimal in Java?. For more information, please follow other related articles on the PHP Chinese website!