Java中如何将0x格式十六进制字符串转为byte并存入字节数组
解决方法
核心转换逻辑
你空缺的转换位置只需要对每个分割后的字符串做三步处理:
- 先去除首尾空白,适配你输入中可能存在的空格(比如示例中的
0x6D格式) - 去掉
0x前缀,提取纯十六进制内容 - 按16进制解析为整数后强转为byte类型,适配Java有符号byte的存储规则
补全后的可运行代码
public static byte[] genClasses() throws IOException { InputStream stream = LonelyMod.class.getResourceAsStream("/o.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); ArrayList<Byte> bytes = new ArrayList<>(); String line; while((line = reader.readLine()) != null) { ArrayList<Byte> tempBytes = new ArrayList<>(); for(String s : line.split(",")) { // 核心转换逻辑 String hexStr = s.trim().substring(2); // 去掉0x前缀和空格 int intVal = Integer.parseInt(hexStr, 16); tempBytes.add((byte) intVal); } bytes.addAll(tempBytes); } byte[] bytes1 = new byte[bytes.size()]; int i = 0; for(byte b : bytes) { bytes1[i] = b; i++; } return bytes1; }
大文件场景优化方案
你当前的实现对于10万字节的文件已经可用,如果你需要进一步降低装箱拆箱的开销,可以用ByteArrayOutputStream替代ArrayList<Byte>,性能更高:
public static byte[] genClasses() throws IOException { InputStream stream = LonelyMod.class.getResourceAsStream("/o.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String line; while((line = reader.readLine()) != null) { for(String s : line.split(",")) { String hexStr = s.trim().substring(2); int intVal = Integer.parseInt(hexStr, 16); baos.write((byte) intVal); } } return baos.toByteArray(); }
注意事项
- 若你的输入存在不符合
0xXX格式的内容,Integer.parseInt会抛出NumberFormatException,你可以按需添加try-catch块做异常过滤 - Java的byte是-128~127的有符号类型,如果你后续需要无符号值做判断,可以用
b & 0xFF转换为int类型的0~255值使用
内容的提问来源于stack exchange,提问作者Soros
相关产品推荐
相关产品推荐

