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 }.

3
  • 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. Commented Aug 17, 2018 at 6:59
  • @JBNizetI am expecting like this is "FF0A" --> byte[] {FF, OA} Commented Aug 17, 2018 at 7: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 } Commented Aug 17, 2018 at 7:46

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to create a byte array of string "FF" instead of representation as "-1".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.