Sunday 26 May 2019

Java: Convert string to hexa string


Below snippet converts a string to hexa string.

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);
}

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[] hexaByteArray) {
  return DatatypeConverter.printHexBinary(hexaByteArray);
 }

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

 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 hexaByteArrayToHexaString = toHexaString(hexaByteArray);
  String actualString = hexaToString(hexaByteArrayToHexaString);

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

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

 }

}

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


You may like

No comments:

Post a Comment