You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

转换十六进制字符串为二进制时触发StringIndexOutOfBoundsException问题排查

排查StringIndexOutOfBoundsException在hexToBinary方法中的问题

从你描述的场景来看,这个异常大概率是因为传入hexToBinary的十六进制字符串不符合方法的预期格式,再加上堆栈信息缺失,咱们可以从这几个方向逐步排查:

可能的触发原因

  • 输入字符串为空或长度不匹配:如果你的hexToBinary方法是为了生成8位二进制字符串,那它大概率预期输入是2位十六进制字符(因为2位十六进制刚好对应8位二进制,范围00-FF)。如果传入的opcode或operand是空字符串、长度为1或者超过2的字符串,方法里如果直接通过charAt()去取固定索引的字符,就会直接抛出索引越界异常。
  • 工具方法内部的硬编码索引问题:比如hexToBinary里写死了要取字符串的第2个字符(charAt(1)),但实际传入的字符串只有1位,这时候必然触发异常。

排查与修复步骤

  1. 提前校验输入参数
    在调用hexToBinary之前,先检查opcode和operand的合法性,避免无效参数流入工具方法:

    // 校验是否为1-2位的有效十六进制字符串
    private boolean isValidHex(String hex) {
        return hex != null && hex.matches("[0-9A-Fa-f]{1,2}");
    }
    
    // 在业务方法中先做校验
    if (!isValidHex(opcode) || !isValidHex(operand)) {
        throw new IllegalArgumentException("Invalid hex input: opcode=" + opcode + ", operand=" + operand);
    }
    
  2. 修复hexToBinary方法
    优化工具方法,让它能兼容1位或2位的十六进制输入,同时始终返回8位二进制字符串,加入明确的参数校验:

    public static String hexToBinary(String hex) {
        // 非空校验
        if (hex == null || hex.isEmpty()) {
            throw new IllegalArgumentException("Hex string cannot be null or empty");
        }
        // 非法字符校验
        if (!hex.matches("[0-9A-Fa-f]+")) {
            throw new IllegalArgumentException("Invalid hex characters: " + hex);
        }
        // 补前导0到2位,确保转换后是8位二进制
        String paddedHex = hex.length() == 1 ? "0" + hex : hex;
        // 限制长度,避免过长的十六进制字符串
        if (paddedHex.length() > 2) {
            throw new IllegalArgumentException("Hex string too long for 8-bit binary: " + hex);
        }
        // 转换为二进制并补前导0到8位
        int decimalValue = Integer.parseInt(paddedHex, 16);
        return String.format("%8s", Integer.toBinaryString(decimalValue)).replace(' ', '0');
    }
    
  3. 添加调试日志定位问题
    因为堆栈信息没给出具体触发位置,你可以在调用hexToBinary前后打印参数值,快速捕获异常输入:

    System.out.println("Converting hex strings: opcode=" + opcode + ", operand=" + operand);
    String opcodeBinary = hexToBinary(opcode);
    String operandBinary = hexToBinary(operand);
    

这样调整后,不管是空字符串、长度不符还是非法字符,都能提前抛出明确的异常,或者通过日志定位到问题输入,再也不会出现模糊的索引越界异常了。

内容的提问来源于stack exchange,提问作者user9398106

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:51:17