Search code examples
javastringintegerhex

Convert string of hex-encoded integers to int array in Java


For example, we have a string "c4d2", known it is a little-endian coded 16-bit int 53956. (It is NOT about conversion "c4d2" to int[] {0xc4, 0xd2}, but about coversion of "c4d2" to integer 53956). How to convert the string to int use Java?

Use python I do

s = b'\xc4\xd2'
n = int.from_bytes(s, "little")
print(f"{s} -> {n}")

output is right

b'\xc4\xd2' -> 53956

Use Java I do

String s = "c4d2"; // 53956
byte[] b = HexFormat.of().parseHex(s);
int n = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getShort();
System.out.println(s + " -> " + Arrays.toString(b) + " -> " + n);

and got

c4d2 -> [-60, -46] -> -11580

that is wrong. But if I do conversion through binary string as

String s2 = Integer.toBinaryString(0xd2) + Integer.toBinaryString(0xc4);
int n2 = Integer.parseInt(s2, 2);
System.out.println(s + " -> " + s2 + " -> " + n2);

I got

c4d2 -> 1101001011000100 -> 53956

the result is right, but the method seems stange.

How to properly convert hex-string to int?


Solution

  • Java's short is signed, so its max value is 32767 and you got overflow. You can use Short.toUnsignedInt():

        String s = "c4d2"; // 53956
        byte[] b = HexFormat.of().parseHex(s);
        int n = Short.toUnsignedInt(ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getShort());
        System.out.println(s + " -> " + Arrays.toString(b) + " -> " + n);
    

    prints

    c4d2 -> [-60, -46] -> 53956