×

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

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.