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
Final Result: JavaScript Increment ... x
Final Result: JavaScript Increment Counter

Leave a Comment

Sign up to our newsletter!

ADB Commands Android Android Applications Android Build system 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, Debugging and Performance Tools Development and Build 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 NDK / Middleware / HAL Operating System 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 Embedded Linux