【问题标题】:Hexadecimal to signed 32-bit conversion十六进制到带符号的 32 位转换
【发布时间】:2014-12-14 06:28:06
【问题描述】:

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

【问题讨论】:

    标签: java android hex decimal


    【解决方案1】:

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

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

    【讨论】:

    • 它没有给出负值。它给出了 4294966062
    • 为什么会出现负数?您需要将其转换为 int 吗?如您所料,请参阅我编辑的答案 -1234。
    • 我正在从 RFDuino 获取十六进制值到我的 android 设备,并且需要将其转换为十进制,所以我需要从 RFDiuno 发送到十进制的确切值,这就是为什么需要负数。但是您编辑的答案说不能从 long 转换为 int。我现在该怎么办。感谢您的回复
    • 您是否完全按照上述方式进行操作?它对我有用,所以也应该对你有用。请同时粘贴跟踪。
    • 我正在这样做。但它在第 2 行显示错误 Long outputDecimal = Long.parseLong("4D2", 16); int number = (int)outputDecimal;
    【解决方案2】:

    使用 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
    

    【讨论】:

    • OP 的数字不适合 int 的范围,因此如果 OP 使用 parseInt 方法,OP 会得到 NumberFormatException。
    猜你喜欢
    • 1970-01-01
    • 2014-04-11
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2011-03-05
    • 2013-12-26
    • 2013-05-28
    相关资源
    最近更新 更多