为什么Java会抛出NumberFormatException [英] why Java throws a NumberFormatException

查看:72
本文介绍了为什么Java会抛出NumberFormatException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将字符串解析为byte时出现异常

I got an exception while parsing a string to byte

String Str ="9B7D2C34A366BF890C730641E6CECF6F";

String [] st=Str.split("(?<=\\G.{2})");

byte[]bytes = new byte[st.length];
for (int i = 0; i <st.length; i++) {
 bytes[i] = Byte.parseByte(st[i]);
}


推荐答案

那是因为默认的解析方法期望一个十进制格式的数字来解析十六进制数,使用这个解析

That's because the default parse method expects a number in decimal format, to parse hexadecimal number, use this parse:

Byte.parseByte(st[i], 16);

其中16是解析的基础。

Where 16 is the base for the parsing.

至于你的评论,你是对的。字节的最大值为0x7F。因此,您可以将其解析为 int 并使用 0xff 执行二进制AND操作以获取LSB,即您的字节:

As for your comment, you are right. The maximum value of Byte is 0x7F. So you can parse it as int and perform binary AND operation with 0xff to get the LSB, which is your byte:

bytes[i] = Integer.parseInt(st[i], 16) & 0xFF;

这篇关于为什么Java会抛出NumberFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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