×

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0.

Hex String - Just as a binary string only consists of 0s and 1s, a hex strings is made up of the numerals 0 through 9 and the letters A through F. Like the hexadecimal string "245FC."

Example:

The aim is to translate a byte array into a hex string given a byte array.

1. byteArray = 9, 2, 14, 10 as an input

Results: 9 2 E A

2. byteArray = 7, 12, 13, and 127 as an input

Results: 7 C D 7F

A byte datatype array is converted towards its hexadecimal value as a string when it is converted from a Byte Array into Hex String. There are several ways to accomplish the same thing; some of them are described here.

Approaches:

  • Using Java's Format() Method
  • Bitwise shift operators are used
  • Using the Integer/Long Class's default method
  • Java's BigInteger Representation in Hexadecimal

Method 1: Using Java's Format()

The requested conversion can be performed using Java's String Format() function. For this,

Calculate the hexadecimal equivalent for every byte in the array by iterating through the bytes in the array.

When printing a hexadecimal value's number of places and storing the result in a string, the string.format() function is utilized.

A hexadecimal (X) value is printed with two spaces between adjacent hexadecimal values using the formatting %02X.

Example Program

import java.io.*;
public class Demo {
public static void convertByteToHex(byte[] byteArray)
{
String hex = "";
for (byte i :byteArray) {
hex += String.format("%02X", i);
}
System.out.print(hex);
}
public static void main(String[] args)
{
byte[] byteArray = { 3, 13, 12, 16 };
convertByteToHex(byteArray);
}
}

Output

030D0C10

Method 2: Utilizing Bitwise Shift Operators

When using the prior method, the process becomes cumbersome as the byte array grows larger. To improve performance, the byte array is transformed into a hexadecimal value using a byte operation.

The right shift operator with no sign is used in this case, ">>>." Additionally, the toCharArray() method turns the supplied string into a string of characters.

 Example program

import java.io.*;
public class Demo {
public static void
convertByteToHex(byte[] byteArray)
{
    int len = byteArray.length;
char[] hexValues = "0123456789ABCDEF".toCharArray();
char[] hexCharacter = new char[len * 2];
for (int i = 0; i<len; i++) {
int v = byteArray[i] & 0xFF;
hexCharacter[i * 2] = hexValues[v >>> 4];
hexCharacter[i * 2 + 1] = hexValues[v & 0x0F];
}
System.out.println(hexCharacter);
}
public static void main(String[] args)
{
byte[] bytes = { 8, 3, 12, 14 };
convertByteToHex(bytes);
}
}

Output

08030C0E

Method 3: Using the Integer/Long Class predefined method

An integer can be converted to its hexadecimal counterpart using the toHexString() function of the Integer class. Now, we must utilize this method to convert every byte array into such an integer (for 4-sized arrays) or long (for 8-sized arrays). The wrap function of a ByteBuffer class can be used to convert a byte array to an integer or long.

 Example Program

import java.io.*;
import java.nio.*;


public class Demo {
public static String toHexadecimal(byte[] bytes)
{
StringBuilder result = new StringBuilder();


for (byte i : bytes) {
int decimal = (int)i& 0XFF;
String hex = Integer.toHexString(decimal);


if (hex.length() % 2 == 1) {
hex = "0" + hex;
}


result.append(hex);
}
return result.toString();
}


public static void main(String[] args)
{
byte[] byteArray = { 8, 3, 13, 12 };
System.out.println(toHexadecimal(byteArray));
}
}

Output

08030d0c

Method 4: Java BigInteger Representation in Hexadecimal

Due to its sluggish speed, Java's Hexadecimal Version of BigInteger class is often avoided when converting byte arrays to hex strings. Furthermore, since we are dealing with numerals and not just any old byte string, leading zeros may occasionally be omitted.

Example Program

import java.io.*;
import java.math.BigInteger;
public class Demo {
public static void toHexString(byte[] byteArray)
{
System.out.print(
new BigInteger(1, byteArray).toString(16));
}
public static void main(String[] args)
{
byte[] byteArray = { 18, 3, 15, 12 };
toHexString(byteArray);
}
}

Output

12030f0c

Related Topics

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.