十六进制到带符号的32位转换

时间:2014-12-14 06:28:07

标签: java android hex decimal

我想将十六进制值转换为带符号的十进制数。比如FFFFFB2E到-1234。在java中有没有任何方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

使用Long.parseLong将16作为您输入的数字的基数,如下所示:

long myHexNumber = Long.parseLong("FFFFFB2E", 16);
int number = (int)myHexNumber;
System.out.println(number);

答案 1 :(得分:0)

使用Integer.parseInt(String,int),每Java documentation

Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned.
An exception of type NumberFormatException is thrown if any of the following situations occurs:

The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.
The value represented by the string is not a value of type int.
Examples:

 parseInt("0", 10) returns 0
 parseInt("473", 10) returns 473
 parseInt("+42", 10) returns 42
 parseInt("-0", 10) returns 0
 parseInt("-FF", 16) returns -255
 parseInt("1100110", 2) returns 102
 parseInt("2147483647", 10) returns 2147483647
 parseInt("-2147483648", 10) returns -2147483648
 parseInt("2147483648", 10) throws a NumberFormatException
 parseInt("99", 8) throws a NumberFormatException
 parseInt("Kona", 10) throws a NumberFormatException
 parseInt("Kona", 27) returns 411787