Java program to convert byte array to hexadecimal
Here is a Java program to convert a byte array to a hexadecimal string:
public class ByteArrayToHex { public static void main(String[] args) { byte[] byteArray = {10, 11, 12, 13, 14, 15}; String hexString = byteArrayToHexString(byteArray); System.out.println(hexString); } public static String byteArrayToHexString(byte[] byteArray) { StringBuilder hexString = new StringBuilder(); for (byte b : byteArray) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } }
This program first creates a byte array, byteArray
, containing some values. It then calls the byteArrayToHexString()
method to convert the byte array to a hexadecimal string. The byteArrayToHexString()
method converts each byte to its hexadecimal representation using the Integer.toHexString()
method, which returns a string containing the hexadecimal representation of the input value. The 0xff & b
operation is used to ensure that the byte value is interpreted as an unsigned value. The method then appends each hexadecimal representation to a StringBuilder
object, adding a leading zero if necessary to ensure that each representation is two characters long. Finally, it returns the completed hexadecimal string.
When you run this program, it will output the hexadecimal string "0a0b0c0d0e0f", which is the hexadecimal representation of the byte values in the byteArray
.