0

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);
}
Community
  • 1
  • 1
Timmay
  • 158
  • 1
  • 2
  • 16
  • Show us the *converting back* function, the above code looks good considering you create byte array of size len/2, so it is impossible to put there 9*2 bytes instead of 8*2 if the input was 16 chars. – Krzysztof Krasoń Jul 29 '16 at 14:13
  • Are you sure the code you are running and the code you are showing are the same? Cause, for me using Java 8, assertEquals(8, buf.length) is true. – wallenborn Jul 29 '16 at 14:21
  • @krzyk Not that it changes in, but I have added it. Try it on your end. – Timmay Jul 29 '16 at 14:37
  • @wallenborn Yes the code is the came. Try it with that string I added. My path says Java SDK is "1.8.0_60" – Timmay Jul 29 '16 at 14:38
  • Your code looks OK. The problem must be somewhere else. Are you sure that the input string's length is exactly 16 characters and that there are no hidden extra characters? – Jesper Jul 29 '16 at 15:01
  • 1
    I also tried running the code by using: `System.out.println(byteArrayToHexString(hexStringToByteArray("FEDCBA9876543210")));` and it outputs `fedcba9876543210`. You must be doing something else wrong. – Krzysztof Krasoń Jul 29 '16 at 15:07
  • Yes I was doing something wrong. – Timmay Aug 01 '16 at 07:40

1 Answers1

0

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();
Timmay
  • 158
  • 1
  • 2
  • 16