0

I am having a hard time trying to convert a String containing the hex string representation to its corresponding hex string byte array.

I tried this code

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)) & 0xFF);
    }
    return data;
}

It's not the exact value what i am looking for above code conveting "FF" --> -1.

Expecting is "FF" --> byte[] { FF }.

Ex : "01FF0A2357F01A" result should be like this byte[] { 01 FF 0A 12 57 F0 1A }.

RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
  • Your question doesn't make sense. A byte array contains bytes, not characters. bytes are numbers, going from -127 to 128. One alternate way of representing them is to use a pair of characters from 0 to F: that's called the hexadecimal representation. Just like the numer 1000 can be represented as a string using 1K. But 1K still means the number 1000. – JB Nizet Aug 17 '18 at 06:59
  • @JBNizetI am expecting like this is "FF0A" --> byte[] {FF, OA} – RajaReddy PolamReddy Aug 17 '18 at 07:43
  • @Scary Wombat .. This is not a duplicate question that marked answer returning "FF" as -1 but i am expecting it as "FF" --> byte [] { FF } – RajaReddy PolamReddy Aug 17 '18 at 07:46

1 Answers1

1

I think your expectations are not quite right but,

    String hex = "ff";
    Integer i = Integer.valueOf(hex, 16);
    System.out.println(i);
    Byte b = i.byteValue();
    System.out.println(b);
    System.out.println(Integer.toHexString(i));

FF is the string representation of -1 in hex

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64