16 bit hex string to signed int in Java

余生长醉 提交于 2019-12-06 18:53:55

问题


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.


回答1:


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



回答2:


try

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


来源:https://stackoverflow.com/questions/15202958/16-bit-hex-string-to-signed-int-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!