I am trying to convert byte[] to Hex string and same Hex string to byte[] in android , data got mismatched.
Ex :
Received byte[] data : [B@b39c86a
converted Hex string : 8be897cc3c4d9e5dd6a6bbd106d8e8d487691b56
When I decode the hex string, I am getting [B@ea6d15b, but its should be [B@b39c86a
I am using below code to convert.
public String byte2hex(byte[] a) {
/*StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();*/
String hexString = "";
for(int i = 0; i < a.length; i++){
String thisByte = "".format("%x", a[i]);
hexString += thisByte;
}
return hexString;
}
public static byte[] hexStringToByteArray(String s) {
/* int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;*/
byte[] bytes = new byte[s.length() / 2];
for(int i = 0; i < s.length(); i += 2){
String sub = s.substring(i, i + 2);
Integer intVal = Integer.parseInt(sub, 16);
bytes[i / 2] = intVal.byteValue();
String hex = "".format("0x%x", bytes[i / 2]);
}
return bytes;
}