Java中的十六进制到整数格式格式异常 [英] hex to int number format exception in java

查看:110
本文介绍了Java中的十六进制到整数格式格式异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试获取数字格式异常

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

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

if I reduce one of the digits in the hex number it converts but not otherwise. why and how to solve this problem?

推荐答案

这将导致整数溢出,因为整数始终使用Java进行签名.从该方法的文档(重点是我的):

This would cause an integer overflow, as integers are always signed in Java. From the documentation of that method (emphasis mine):

如果发生以下任何一种情况,将引发类型为NumberFormatException的异常:

  • 第一个参数为null或长度为零的字符串.
  • 基数小于Character.MIN_RADIX或大于Character.MAX_RADIX.
  • 该字符串的任何字符都不是指定基数的数字,除非第一个字符可以是减号'-'('\ u002D'),前提是该字符串长于长度1.
  • 该字符串表示的值不是int类型的值.
  • 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.

它将装入一个 un 有符号整数.从Java 8开始, Andreas ):

It would fit into an unsigned integer, though. As of Java 8 there's Integer.parseUnsignedInt (thanks, Andreas):

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

在早期的Java版本上,最好的选择是使用long,然后将long的低4个字节放入int:

On earlier Java versions your best bet here might to use a long and then just put the lower 4 bytes of that long into an int:

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

也许您甚至可以删除按位和"在这里,但我现在无法测试.但这可能会将其缩短为

Maybe you can even drop the bitwise "and" here, but I can't test right now. But that could shorten it to

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

这篇关于Java中的十六进制到整数格式格式异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆