You need a simple class utility here . The following is an example in which we convert from a hex string to a byte[] , and then to a hex string , and then we compare it to make sure the conversion was good.
public class Test { public static void main(String[] args) { String str = ""; String str1 = new String(encodeHex(hexStringToByteArray(str))); if (str1.equals(str)) { System.out.println("String matches "); } } public static byte[] hexStringToByteArray(String str) { char[] data = str.toCharArray(); int len = data.length; byte[] out = new byte[len >> 1]; for (int i = 0, j = 0; j < len; i++) { int f = Character.digit(data[j], 16) << 4; j++; f = f | Character.digit(data[j], 16); j++; out[i] = (byte) (f & 0xFF); } return out; } public static char[] encodeHex(byte[] data) { int l = data.length; char[] out = new char[l << 1]; for (int i = 0, j = 0; i < l; i++) { out[j++] = DIGITS[(0xF0 & data[i]) >>> 4]; out[j++] = DIGITS[0x0F & data[i]]; } return out; } private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; }
Output:
String matches
source share