16 位十六进制字符串到 Java 中的有符号整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15202958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
16 bit hex string to signed int in Java
提问by Dimme
I have a string in Java representing a signed 16-bit value in HEX. This string can by anything from "0000"
to "FFFF"
.
我有一个用 Java 表示的字符串,用十六进制表示一个有符号的 16 位值。这个字符串可以是从"0000"
到的任何东西"FFFF"
。
I use Integer.parseInt("FFFF",16)
to convert it to an integer. However, this returns an unsigned value (65535
).
我Integer.parseInt("FFFF",16)
用来将其转换为整数。但是,这将返回一个无符号值 ( 65535
)。
I want it to return a signed value. In this particular example "FFFF"
should return -1
.
我希望它返回一个有符号的值。在这个特定的例子中"FFFF"
应该返回-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.
我怎样才能做到这一点?由于它是一个 16 位值,我想使用,Short.parseShort("FFFF",16)
但这告诉我我超出了范围。我想parseShort()
预计会出现负号。
回答by Andreas Fester
You can cast the int
returned from Integer.parseInt()
to a short:
您可以将int
返回的从Integer.parseInt()
转换为短:
short s = (short) Integer.parseInt("FFFF",16);
System.out.println(s);
Result:
结果:
-1
回答by Evgeniy Dorofeev
try
尝试
int i = (short) Integer.parseInt("FFFF", 16);