2的补码十六进制数到java中的十进制数 [英] 2's complement hex number to decimal in java
本文介绍了2的补码十六进制数到java中的十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个十六进制字符串,表示2的补码数。有没有一种简单的方法(库/函数)将十六进制转换为十进制而不直接使用它的位?
E.G。这是给定左边的十六进制的预期输出:
0000=> 0
7FFF=> 32767(最大正数)
8000=> -32768(最大负数)
FFFF=> -1
谢谢!
解决
Integer.valueOf ( FFFF,16).shortValue(); //评估结果为-1(短)
当然这类东西只适用于8,16 ,32和64位2的补码:
Short.valueOf(FF,16).byteValue(); // -1(byte)
Integer.valueOf(FFFF,16).shortValue(); // -1(short)
Long.valueOf(FFFFFFFF,16).intValue(); // -1(int)
new BigInteger(FFFFFFFFFFFFFFFF,16).longValue(); // -1(long)
示例这里。
I have a hex string that represents a 2's complement number. Is there an easy way (libraries/functions) to translate the hex into a decimal without working directly with its bits??
E.G. This is the expected output given the hex on the left:
"0000" => 0
"7FFF" => 32767 (max positive number)
"8000" => -32768 (max negative number)
"FFFF" => -1
Thanks!
解决方案
This seems to trick java into converting the number without forcing a positive result:
Integer.valueOf("FFFF",16).shortValue(); // evaluates to -1 (short)
Of course this sort of thing only works for 8, 16, 32, and 64-bit 2's complement:
Short.valueOf("FF",16).byteValue(); // -1 (byte)
Integer.valueOf("FFFF",16).shortValue(); // -1 (short)
Long.valueOf("FFFFFFFF",16).intValue(); // -1 (int)
new BigInteger("FFFFFFFFFFFFFFFF",16).longValue(); // -1 (long)
这篇关于2的补码十六进制数到java中的十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文