有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    使用String.split()将字符串分解为单个字节,使用Integer.parseInt(s, 16)将字符串表示形式转换为整数

    像这样的方法应该有用:

    List<Integer> parseHex(String hex) {
        ArrayList<Integer> a = new ArrayList<Integer>();
        for (String s : hex.split("\\s+")) {
              a.add(Integer.parseInt(s, 16));
        }
        return a;
    }
    
  2. # 3 楼答案

    由于您提到更喜欢字节数组,因此可以使用字节缓冲来累积字节值:

    String text = "20 0F 01";
    
    ByteBuffer buffer = ByteBuffer.allocate((text.length() + 1) / 3);
    Scanner scanner = new Scanner(text);
    while (scanner.hasNextInt(16)) {
        buffer.put((byte) scanner.nextInt(16));
    }
    
    byte[] bytes = buffer.array();
    

    我们使用hasNextInt和nextInt,而不是hasNextByte和nextByte,因为Java的数字类型是有符号的,并且7f以上的值不能表示为有符号字节