-1

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?

6
  • Your question title says you want to convert the hex-string to an int []. But. in your example where you use Integer.toBinaryString, the end result is an int. So, which is the desired result? Commented Jun 28, 2023 at 18:38
  • 1
    Java's short is signed, so its max value is 32767 and you got overflow. Commented Jun 28, 2023 at 18:38
  • 1
    Does this answer your question? Convert hex little endian String to int in java Commented Jun 28, 2023 at 18:40
  • In general, I want to convert a string which codes array of 16-bit integers (so, two bytes per int) to int array. But in example string "c4d2" shold be converted to int. Commented Jun 28, 2023 at 18:42
  • int n = new BigInteger("c4d2", 16).intValue(); Commented Jun 28, 2023 at 22:27

2 Answers 2

1

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

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

Comments

1

One approach would be to reverse the values, and then use the Integer#parseInt method, specifying a 16 for the radix.

String string = "c4d2";
StringBuilder reversed = new StringBuilder();
for (int index = string.length() - 1; index >= 0; index -= 2)
    reversed.append(string, index - 1, index + 1);
int number = Integer.parseInt(reversed.toString(), 16);

Output, for number.

53956

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.