- Java Program to Convert Byte Array to Hexadecimal
- Example 1: Convert Byte Array to Hex value
- Example 2: Convert Byte Array to Hex value using byte operations
- Print bytes as hex java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Convert Byte Array in Hex String in Java
- HEX_ARRAY[] Method to Convert Byte Array to Hex String in Java
- Hex.encodeHexString() Method to Convert Byte Array to Hex String in Java
- DatatypeConverter() Method to Convert Byte Array in Hex String in Java
- append(.format) Method for Conversion of Byte Array Into Hex String in Java
- Related Article — Java Array
- Related Article — Java String
- Class HexFormat
Java Program to Convert Byte Array to Hexadecimal
To understand this example, you should have the knowledge of the following Java programming topics:
Example 1: Convert Byte Array to Hex value
public class ByteHex < public static void main(String[] args) < byte[] bytes = ; for (byte b : bytes) < String st = String.format("%02X", b); System.out.print(st); >> >
In the above program, we have a byte array named bytes . To convert byte array to a hex value, we loop through each byte in the array and use String ‘s format() .
We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st .
This is a relatively slower process for large byte array conversion. We can dramatically increase the speed of execution using byte operations shown below.
Example 2: Convert Byte Array to Hex value using byte operations
public class ByteHex < private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) < char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) < int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; > return new String(hexChars); > public static void main(String[] args) < byte[] bytes = ; String s = bytesToHex(bytes); System.out.println(s); > >
The output of the program is the same as Example 1.
Print bytes as hex java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Convert Byte Array in Hex String in Java
- HEX_ARRAY[] Method to Convert Byte Array to Hex String in Java
- Hex.encodeHexString() Method to Convert Byte Array to Hex String in Java
- DatatypeConverter() Method to Convert Byte Array in Hex String in Java
- append(.format) Method for Conversion of Byte Array Into Hex String in Java
We have introduced how to convert byte array to string in Java in another article. In this tutorial, we will learn how to convert byte array to hex string in Java.
HEX_ARRAY[] Method to Convert Byte Array to Hex String in Java
The first method we will be starting with, for this conversion we will use HEX_ARRAY[] consisting of all possible hex values. This method is faster than any other alternative.
public class SimpleTesting char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); byte b[]= new byte[2]; b[0] = 20; b[1] = 10; char[] hexChars = new char[b.length * 2]; for (int j = 0; j b.length; j++) int v = b[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; > System.out.println(hexChars); > >
Hex.encodeHexString() Method to Convert Byte Array to Hex String in Java
The second method to convert byte array to hex string in Java is Hex.encodeHexString() method. Since its an apache ’s commons library, hence method apache.commons.codec.binary.Hex() needs to be imported first inside the compiler.
import java.util.Arrays; import org.apache.commons.codec.binary.Hex; public class SimpleTesting public static void main(String[] args) byte[] byteArray = new byte[] 'S', 'i', 'm', 'p', 'l', 'e', 'T', 'e', 's', 't', 'i', 'n', 'g'>; System.out.println("Byte Array: "); System.out.println(Arrays.toString(byteArray)); System.out.println("Hex String Conversion: " + Hex.encodeHexString(byteArray)); > >
Byte Array: Simple Testing Hex String Conversion: 53696d706c652054657374696e67
DatatypeConverter() Method to Convert Byte Array in Hex String in Java
Another approach is javax.xml.bind.DatatypeConverter.printHexBinary() method in Java. This method takes the bytes and converts it into Hex from an array.
import java.util.Arrays; public class SimpleTesting public static void main(String[] args) byte byteArray[] = <(byte)00, (byte)10, (byte)20, (byte)30, (byte)40>; String hexString = javax.xml.bind.DatatypeConverter .printHexBinary(byteArray); System.out.println("Byte Array: "); System.out.println(Arrays.toString(byteArray)); System.out.println("Hex String Conversion: " + hexString); > >
Byte Array: [0, 10, 20, 30, 40] Hex String Conversion: 000A141E28
append(.format) Method for Conversion of Byte Array Into Hex String in Java
Another method that can be used is to include append(.format) using stringBuilder in Java. It works by converting every single value from byte array and convert one by one to hex string accordingly.
public class SimpleTesting public static void main(String[] args) byte a[]= new byte[2]; a[0] = 20; a[1] = 10; StringBuilder sb = new StringBuilder(a.length * 2); for(byte b: a) sb.append(String.format("%02x", b)); System.out.println(sb); > >
Related Article — Java Array
Related Article — Java String
Class HexFormat
HexFormat converts between bytes and chars and hex-encoded strings which may include additional formatting markup such as prefixes, suffixes, and delimiters.
There are two factories of HexFormat with preset parameters of() and ofDelimiter(delimiter) . For other parameter combinations the withXXX methods return copies of HexFormat modified withPrefix(String) , withSuffix(String) , withDelimiter(String) or choice of withUpperCase() or withLowerCase() parameters.
For primitive to hexadecimal string conversions the toHexDigits methods include toHexDigits(byte) , toHexDigits(int) , and toHexDigits(long) , etc. The default is to use lowercase characters «0-9″,»a-f» . For conversions producing uppercase hexadecimal the characters are «0-9″,»A-F» . Only the HexFormat.isUpperCase() parameter is considered; the delimiter, prefix and suffix are not used.
For hexadecimal string to primitive conversions the fromHexDigits methods include fromHexDigits(string) , fromHexDigitsToLong(string) , and fromHexDigit(int) converts a single character or codepoint. For conversions from hexadecimal characters the digits and uppercase and lowercase characters in «0-9», «a-f», and «A-F» are converted to corresponding values 0-15 . The delimiter, prefix, suffix, and uppercase parameters are not used.
For byte array to formatted hexadecimal string conversions the formatHex methods include formatHex(byte[]) and formatHex(Appendable, byte[]) . The formatted output is a string or is appended to an Appendable such as StringBuilder or PrintStream . Each byte value is formatted as the prefix, two hexadecimal characters from the uppercase or lowercase digits, and the suffix. A delimiter follows each formatted value, except the last. For conversions producing uppercase hexadecimal strings use withUpperCase() .
For formatted hexadecimal string to byte array conversions the parseHex methods include parseHex(CharSequence) and parseHex(char[], offset, length) . Each byte value is parsed from the prefix, two case insensitive hexadecimal characters, and the suffix. A delimiter follows each formatted value, except the last.
API Note: For example, an individual byte is converted to a string of hexadecimal digits using toHexDigits(int) and converted from a string to a primitive value using fromHexDigits(string) .
HexFormat hex = HexFormat.of(); byte b = 127; String byteStr = hex.toHexDigits(b); byte byteVal = (byte)hex.fromHexDigits(byteStr); assert(byteStr.equals("7f")); assert(b == byteVal); // The hexadecimal digits are: "7f"
For a comma ( «, » ) separated format with a prefix ( «#» ) using lowercase hex digits the HexFormat is:
HexFormat commaFormat = HexFormat.ofDelimiter(", ").withPrefix("#"); byte[] bytes = ; String str = commaFormat.formatHex(bytes); byte[] parsed = commaFormat.parseHex(str); assert(Arrays.equals(bytes, parsed)); // The formatted string is: "#00, #01, #02, #03, #7c, #7d, #7e, #7f"
For a fingerprint of byte values that uses the delimiter colon ( «:» ) and uppercase characters the HexFormat is:
HexFormat formatFingerprint = HexFormat.ofDelimiter(":").withUpperCase(); byte[] bytes = ; String str = formatFingerprint.formatHex(bytes); byte[] parsed = formatFingerprint.parseHex(str); assert(Arrays.equals(bytes, parsed)); // The formatted string is: "00:01:02:03:7C:7D:7E:7F"
This is a value-based class; use of identity-sensitive operations (including reference equality ( == ), identity hash code, or synchronization) on instances of HexFormat may have unpredictable results and should be avoided. The equals method should be used for comparisons.
This class is immutable and thread-safe.
Unless otherwise noted, passing a null argument to any method will cause a NullPointerException to be thrown.