Sunday, 26 May 2019

Java: Convert hexa string to byte array


‘DatatypeConverter’ class provides printHexBinary and parseHexBinary methods to convert bytes to hexa string and string to hexa bytes.

printHexBinary : Converts an array of bytes into a string.
parseHexBinary : Converts the string argument into an array of bytes.

App.java
package com.sample.app;

import javax.xml.bind.DatatypeConverter;

public class App {
 private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();

 public static String toHex(String input) {
  if (input == null)
   throw new NullPointerException();
  return convertToHex(input.getBytes());
 }

 private static String convertToHex(byte[] buf) {
  char[] chars = new char[2 * buf.length];
  for (int i = 0; i < buf.length; ++i) {
   chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
   chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
  }
  return new String(chars);
 }

 public static String toHexaString(byte[] array) {
  return DatatypeConverter.printHexBinary(array);
 }

 public static byte[] hexatoByteArray(String s) {
  return DatatypeConverter.parseHexBinary(s);
 }

 public static String hexaToString(String txtInHex) {
  byte[] txtInByte = new byte[txtInHex.length() / 2];
  int j = 0;
  for (int i = 0; i < txtInHex.length(); i += 2) {
   txtInByte[j++] = Byte.parseByte(txtInHex.substring(i, i + 2), 16);
  }
  return new String(txtInByte);
 }

 private static void printByteArray(byte[] bytes) {
  for (byte data : bytes) {
   System.out.print(data + " ");
  }
  System.out.println();
 }

 public static void main(String args[]) {
  String input = "Hello World";
  String hexaString = toHex(input);
  byte[] hexaByteArray = hexatoByteArray(hexaString);
  String byteArrayToHexaString = toHexaString(hexaByteArray);
  String actualString = hexaToString(byteArrayToHexaString);

  System.out.println("input : " + input);
  System.out.println("hexaString : " + hexaString);
  System.out.print("hexaByteArray : ");
  printByteArray(hexaByteArray);

  System.out.println("byteArrayToHexaString : " + byteArrayToHexaString);
  System.out.println("actualString : " + actualString);

 }

}

Output
input : Hello World
hexaString : 48656C6C6F20576F726C64
hexaByteArray : 72 101 108 108 111 32 87 111 114 108 100
byteArrayToHexaString : 48656C6C6F20576F726C64
actualString : Hello World


You may like

No comments:

Post a Comment