加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java中的十六进制到int数字格式异常

发布时间:2020-12-15 02:01:18 所属栏目:Java 来源:网络整理
导读:我在尝试这样做时遇到了数字格式异常 int temp = Integer.parseInt("C050005C",16); 如果我减少它转换的十六进制数中的一个数字,但不是.为什么以及如何解决这个问题? 解决方法 这会导致整数溢出,因为整数总是用Java签名.从 documentation of that method(强
我在尝试这样做时遇到了数字格式异常

int temp = Integer.parseInt("C050005C",16);

如果我减少它转换的十六进制数中的一个数字,但不是.为什么以及如何解决这个问题?

解决方法

这会导致整数溢出,因为整数总是用Java签名.从 documentation of that method(强调我的):

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’) provided that the string is longer than length 1.
  • The value represented by the string is not a value of type int.

但它会适合无符号整数.但这在Java中没有选择.

所以你最好的选择是使用long,然后将那个long的低4个字节放入int:

long x = Long.parseLong("C050005C",16);
int y = (int)(x & 0xffffffff);

也许你甚至可以在这里按下“和”,但我现在无法测试.但这可能会缩短它

int y = (int)Long.parseLong("C050005C",16);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读