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”


Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


$ 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
lynxbee_ezoic

Leave a Comment

Android Android Build system Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded