dimme
dimme

Reputation: 4424

16 bit hex string to signed int in Java

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.

Upvotes: 12

Views: 13705

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136162

try

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

Upvotes: 2

Andreas Fester
Andreas Fester

Reputation: 36649

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

Upvotes: 16

Related Questions