Am converting a 64 bit/16 hex string to byte array but it seems am not doing the conversion well.
What am I doing wrong?
So my string is FEDCBA9876543210
but when I convert it to byteArray
it is 9 bytes long instead of 8!
On converting it back, I get 00FEDCBA9876543210
What am I doing wrong. This thread was used in my function. Here is my code for the conversion.
public static byte[] hexStringToByteArray(String str) {
int len = str.length();
byte [] data = new byte[len/2];
for (int i=0; i<len; i+=2) {
data[i/2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) +
(Character.digit(str.charAt(i+1), 16)));
}
return data;
}
This is the code for converting back.
public static String byteArrayToHexString(byte [] bytes) {
char[] hexArray = "0123456789abcdef".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int i=0; i<bytes.length; i++) {
int c = bytes[i] & 0xFF;
hexChars[i*2] = hexArray[c >>> 4];
hexChars[i*2 + 1] = hexArray[c & 0x0F];
}
return new String(hexChars);
}