【问题标题】:Convert String to Bytes in Java [duplicate]在Java中将字符串转换为字节[重复]
【发布时间】:2012-06-02 21:19:02
【问题描述】:

可能重复:
Convert a string representation of a hex dump to a byte array using Java?

我有一个 MD5 字符串

de70d4de8c47385536c8e08348032c3b

我需要它作为字节值

DE 70 D4 DE 8C 47 38 55 36 C8 E0 83 48 03 2C 3B

这应该类似于 Perls pack("H32); 函数。

【问题讨论】:

  • 所以你想把字符串从这个:de70d4de8c47385536c8e08348032c3b 转换成这个:DE 70 D4 DE 8C 47 38 55 36 C8 E0 83 48 03 2C 3B
  • 几乎,我不希望这被视为文本文件中的字符串,而是字节。
  • 你能写一个单元测试吗?我不知道你指的是哪种数据类型。
  • @npinti 看起来他需要那个
  • (很多“我如何在 Java 中解析十六进制”的问题——我选择了一个例子。)

标签: java pack


【解决方案1】:

你可以看看 Apache Commons Codec Hex.decodeHex()

【讨论】:

    【解决方案2】:

    遍历String 并使用Byte.decode(String) 函数填充字节数组。

    【讨论】:

    • 例如"de" 不能被Byte.decode 解析,所以我认为它不会起作用。
    • 您需要将“0x”作为前缀。
    【解决方案3】:

    有很多方法可以做到这一点。这是一个:

    public static void main(String[] args) {
    
        String s = "de70d4de8c47385536c8e08348032c3b";
    
        Matcher m = Pattern.compile("..").matcher(s);
    
        List<Byte> bytes = new ArrayList<Byte>();
        while (m.find())
            bytes.add((byte) Integer.parseInt(m.group(), 16));
    
        System.out.println(bytes);
    }
    

    输出(-34 == 0xde):

    [-34, 112, -44, -34, -116, 71, 56, 85, 54, -56, -32, -125, 72, 3, 44, 59]
    

    【讨论】:

      【解决方案4】:

      未验证:

      String md5 = "de70d4de8c47385536c8e08348032c3b";
      byte[] bArray = new byte[md5.length() / 2];
      for(int i = 0, k = 0; i < md5.lenth(); i += 2, k++) {
          bArray[k] = (byte) Integer.parseInt(md5[i] + md5[i+1], 16);
      }
      

      【讨论】:

        猜你喜欢
        • 2012-11-22
        • 1970-01-01
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-22
        相关资源
        最近更新 更多