tylersuehr7 / Hex.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Converts hexadecimal strings. Thread-safe. |
* @author Tyler Suehr |
*/ |
public final class SimpleHex |
private SimpleHex () <> |
/* Hexadecimal character table */ |
private static final char [] DIGITS = «0123456789ABCDEF» . toCharArray (); |
/** |
* Decodes the hexadecimal-encoded string value. |
* |
* @param data the string value to be decoded |
* @return the value |
*/ |
public static byte [] decodeHex ( String data ) throws IllegalStateException |
return decodeHex ( data . toCharArray ()); |
> |
/** |
* Decodes the hexadecimal-encoded char array. |
* |
* @param data the char array to be decoded |
* @return the value |
*/ |
public static byte [] decodeHex ( char [] data ) throws IllegalStateException |
final int dataLen = data . length ; |
if (( dataLen & 0x01 ) != 0 ) |
throw new IllegalStateException ( «Odd number of characters.» ); |
final byte [] out = new byte [ dataLen >> 1 ]; |
int i , j , f ; |
for ( i = 0 , j = 0 ; j < dataLen ; i ++) |
f = toDigit ( data [ j ], j ) |
j ++; |
f = f | toDigit ( data [ j ], j ); |
j ++; |
out [ i ] = ( byte ) ( f & 0xFF ); |
> |
return out ; |
> |
/** |
* Encodes the data as a hexadecimal-encoded char array. |
* |
* @param data the data to be encoded |
* @return the value |
*/ |
public static char [] encodeHex ( byte [] data ) |
final char [] digits = DIGITS ; |
final int dataLen = data . length ; |
final char [] out = new char [ dataLen |
int i , j ; |
for ( i = 0 , j = 0 ; i < dataLen ; i ++) |
out [ j ++] = digits [( 0xF0 & data [ i ]) >>> 4 ]; |
out [ j ++] = digits [ 0x0F & data [ i ]]; |
> |
return out ; |
> |
/** |
* Encodes the data as a hexadecimal-encoded string. |
* |
* @param data the data to be encoded |
* @return the value |
*/ |
public static String encodeHexString ( byte [] data ) |
return new String ( encodeHex ( data )); |
> |
/** |
* Converts a character into a hexadecimal digit. |
* |
* @param ch the character to be converted |
* @param index the index of the character in a sequence |
* @return the digit |
* |
* @throws IllegalStateException if invalid hexadecimal character |
*/ |
private static int toDigit ( char ch , int index ) throws IllegalStateException |
final int digit = Character . digit ( ch , 16 ); |
if ( digit == — 1 ) |
throw new IllegalStateException ( «Illegal hexadecimal character at » + index + «.» ); |
return digit ; |
> |
> |
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.
Java Encode and Decode Hex String using Apache Commons Codec
In this Java tutorial we learn how to use Hex class of Apache Commons Codec library to encode byte[] array to hexadecimal String and decode hexadecimal String to byte[] array.
Table of contents
Add Apache Commons Codec Dependency to Java project
To use Apache Commons Codec library in the Gradle build project, add the following dependency into the build.gradle file.
implementation group: 'commons-codec', name: 'commons-codec', version: '1.15'
To use the Apache Commons Codec library in the Maven build project, add the following dependency into the pom.xml file.
commons-codec commons-codec 1.15
To have more information about the Apache Commons Codec Java library you can visit the project home page at commons.apache.org/proper/commons-codec/
Convert Byte Array to Hex String in Java
With Apache Commons Codec we can use the Hex.encodeHexString() method to convert an byte[] array into hexadecimal string as following Java program.
import org.apache.commons.codec.binary.Hex; public class HexExample1 public static void main(String. args) byte[] inputBytes = "SimpleSolution".getBytes(); String hexString = Hex.encodeHexString(inputBytes); System.out.println(hexString); > >
53696d706c65536f6c7574696f6e
Convert Hex String to Byte Array in Java
We also can decode a hexadecimal String to byte[] array using the Hex.decodeHex() as below.
import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import java.util.Arrays; public class HexExample2 public static void main(String. args) throws DecoderException String hexString = "53696d706c65536f6c7574696f6e"; byte[] outputBytes = Hex.decodeHex(hexString); System.out.println(Arrays.toString(outputBytes)); System.out.println(new String(outputBytes)); > >
[83, 105, 109, 112, 108, 101, 83, 111, 108, 117, 116, 105, 111, 110] SimpleSolution
Convert SHA-1 Hashed Byte Array to Hex String
In the following Java program we show how to use Hex.encodeHexString() to convert SHA-1 hash result from byte[] array to hexadecimal String.
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; public class HexExample3 public static void main(String. args) String inputData = "Simple Solution"; MessageDigest sha1MessageDigest = DigestUtils.getSha1Digest(); byte[] hashedBytes = sha1MessageDigest.digest(inputData.getBytes(StandardCharsets.UTF_8)); String hashedString = Hex.encodeHexString(hashedBytes); System.out.println("Input String:" + inputData); System.out.println("SHA-1:" + hashedString); > >
Input String:Simple Solution SHA-1:23921d0724f0388c797b1383c39a6eaea5c134e6
tylersuehr7 / Hex.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Converts hexadecimal strings. Thread-safe. |
* @author Tyler Suehr |
*/ |
public final class SimpleHex |
private SimpleHex () <> |
/* Hexadecimal character table */ |
private static final char [] DIGITS = «0123456789ABCDEF» . toCharArray (); |
/** |
* Decodes the hexadecimal-encoded string value. |
* |
* @param data the string value to be decoded |
* @return the value |
*/ |
public static byte [] decodeHex ( String data ) throws IllegalStateException |
return decodeHex ( data . toCharArray ()); |
> |
/** |
* Decodes the hexadecimal-encoded char array. |
* |
* @param data the char array to be decoded |
* @return the value |
*/ |
public static byte [] decodeHex ( char [] data ) throws IllegalStateException |
final int dataLen = data . length ; |
if (( dataLen & 0x01 ) != 0 ) |
throw new IllegalStateException ( «Odd number of characters.» ); |
final byte [] out = new byte [ dataLen >> 1 ]; |
int i , j , f ; |
for ( i = 0 , j = 0 ; j < dataLen ; i ++) |
f = toDigit ( data [ j ], j ) |
j ++; |
f = f | toDigit ( data [ j ], j ); |
j ++; |
out [ i ] = ( byte ) ( f & 0xFF ); |
> |
return out ; |
> |
/** |
* Encodes the data as a hexadecimal-encoded char array. |
* |
* @param data the data to be encoded |
* @return the value |
*/ |
public static char [] encodeHex ( byte [] data ) |
final char [] digits = DIGITS ; |
final int dataLen = data . length ; |
final char [] out = new char [ dataLen |
int i , j ; |
for ( i = 0 , j = 0 ; i < dataLen ; i ++) |
out [ j ++] = digits [( 0xF0 & data [ i ]) >>> 4 ]; |
out [ j ++] = digits [ 0x0F & data [ i ]]; |
> |
return out ; |
> |
/** |
* Encodes the data as a hexadecimal-encoded string. |
* |
* @param data the data to be encoded |
* @return the value |
*/ |
public static String encodeHexString ( byte [] data ) |
return new String ( encodeHex ( data )); |
> |
/** |
* Converts a character into a hexadecimal digit. |
* |
* @param ch the character to be converted |
* @param index the index of the character in a sequence |
* @return the digit |
* |
* @throws IllegalStateException if invalid hexadecimal character |
*/ |
private static int toDigit ( char ch , int index ) throws IllegalStateException |
final int digit = Character . digit ( ch , 16 ); |
if ( digit == — 1 ) |
throw new IllegalStateException ( «Illegal hexadecimal character at » + index + «.» ); |
return digit ; |
> |
> |