Timmay Timmay - 10 months ago 35
Java Question

Converting HexString to Bytes and then Back to HexString adds extra zero

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

but when I convert it to
it is 9 bytes long instead of 8!
On converting it back, I get

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


I was making a terrible mistake. Somewhere after the conversion, I was reconverting the BigInteger value of this with BigInteger.toByteArray conversion. (Don't ask me why!!) Remnants of previous work.

According to the documentation here, conversion to byte array adds one sign bit.

On removing the links to this, I now have 8 bytes. :)

this.vendingKey = Conversions.hexStringToByteArray(vendingKey);
BigInteger bigInteger = new BigInteger(vendingKey, 16);
this.vendingKey = bigInteger.toByteArray();