12

I have a string in Java representing a signed 16-bit value in HEX. This string can by anything from "0000" to "FFFF".

I use Integer.parseInt("FFFF",16) to convert it to an integer. However, this returns an unsigned value (65535).

I want it to return a signed value. In this particular example "FFFF" should return -1.

How can I achieve this? Since its a 16-bit value I thought of using Short.parseShort("FFFF",16) but that tells me that I am out of range. I guess parseShort() expects a negative sign.

2 Answers 2

16

You can cast the int returned from Integer.parseInt() to a short:

short s = (short) Integer.parseInt("FFFF",16);
System.out.println(s);

Result:

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

3 Comments

@AndreasFester , why does this require further cast as short?
@Rachael Because the value returned by Integer.parseInt is still a (32 bit) int value - for 0xFFFF, that is 65535. By assigning it to a short, the upper 16 bits are effectively discarded and bit 15 is taken as the sign bit for the short value, resulting in -1 (all bits are 1). The cast is required to tell the compiler that this loss of bits is intended - without the cast, the compiler would complain about possible lossy conversion from int to short
@AndreasFester thank you for that great explanation.
2

try

int i = (short) Integer.parseInt("FFFF", 16);

Comments

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.