Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 203
Dimme Avatar asked Mar 04 '13 13:03

Dimme


People also ask

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

How do you pass a hexadecimal value in Java?

Assuming that we have our hex number in a string, then a simple way to convert the hex number to decimal is to call Integer. parseInt(), passing in 16 as the second parameter: String hexNumber = ... int decimal = Integer.


1 Answers

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
like image 130
Andreas Fester Avatar answered Sep 19 '22 05:09

Andreas Fester