Convert Byte Array to Hex using Java

The post briefs above how you can convert byte Array to Hex values and print those on terminal. You are mostly be needing this conversion when you work closely with byte operations like as needed in network communications etc.

We will take the same example as we used in our another post “Byte Array To Integer And Integer to Byte Array Conversion using JAVA”

 $ vim ByteArrayToHex.java 
import java.io.*;

public class ByteArrayToHex {
        private static String printHex = null;

        public static void main(String[] args) throws Exception {
                byte[] byteArray = {07, 14, 30, 39};
                //print every byte on new line
                for (int i=0; i<byteArray.length; i++) {
                        printHex = String.format("%02X", byteArray[i]);
                        System.out.println("byteArray Dec Value: " + byteArray[i] + " Hex: " + printHex);
                }

                //print in Single Line
                for (int i=0; i<byteArray.length; i++) {
                        printHex = String.format("%02X", byteArray[i]);
                        System.out.print(printHex);
                }
                        //empty new line for clear display
                        System.out.println();
        }
}
 $ javac ByteArrayToHex.java 
 >$ java ByteArrayToHex 
byteArray Dec Value: 7 Hex: 07
byteArray Dec Value: 14 Hex: 0E
byteArray Dec Value: 30 Hex: 1E
byteArray Dec Value: 39 Hex: 27
070E1E27
Follow Lynxbee

Leave a Reply / Ask Question