十六进制格式的字节值,并将这些值写入字节流?

时间:2015-06-08 11:38:36

标签: java

采用十六进制格式的字节值序列,并将这些值写入字节流。       " 01 02 1a" =>将字节0x01 0x02 0x1a写入字节流。

这是什么意思?

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案:

    String hex = "01 02 1a";

    // Remove spaces
    hex = hex.replace(" ", "");

    // Array containing bytes
    byte[] bytes = new byte[hex.length() / 2];

    int k = 0;
    for(int i=0; i < hex.length(); i = i +2 ) {
        // Read and parse each byte
        int b = Integer.parseInt(hex.substring(i, i + 2), 16);
        bytes[k] = (byte) b;
        k++;
    }

    // Write bytes to an outputStram
    OutputStream out;
    for(Byte b: bytes) {
        out.write(b);
    }