有人可以解释java中从字节数组到十六进制字符串的转换

时间:2013-03-31 02:50:47

标签: java arrays hex byte

我最近在寻找一种将字节数组转换为十六进制字符串的编码。 首先,我发现了以下内容:how to convert hex to byte for the following program?

我已经尝试过这个:

StringBuffer stringbuffer = new StringBuffer(cipherbyte.length * 2);
    for (int i = 0; i < cipherbyte.length; i++) {
        if ((cipherbyte[i] & 0xff) < 0x10 ) {
            stringbuffer.append("0");
        }
        stringbuffer.append(Long.toString(cipherbyte[i] & 0xff, 16));
    }
    String ciphertext = stringbuffer.toString();
    return ciphertext;

用于解码:

byte[] bytes = new byte[message.length() / 2];
    for (int i = 0; i < message.length(); i = i+2) {
        String substr = message.substring(i, i+2);
        bytes[i/2] = ((byte) Integer.parseInt(substr, 16));
    } 

但我不知道这些算法如何详细工作,请有人解释一下吗?

1 个答案:

答案 0 :(得分:0)

// create a StringBuffer to hold the ciphertext. Maximum you need double its size if all the byte is 0x0 and 0x9 
StringBuffer stringbuffer = new StringBuffer(cipherbyte.length * 2);


    for (int i = 0; i < cipherbyte.length; i++) { // get each byte
        if ((cipherbyte[i] & 0xff) < 0x10 ) {  // if byte is between 0x0 and 0x9, padding a 0
            stringbuffer.append("0");
        }
        // get current byte as long type and convert into a 16 radix string.
        // this combine the code above if byte is between 0x0 and 0x9
        stringbuffer.append(Long.toString(cipherbyte[i] & 0xff, 16));
    }


    String ciphertext = stringbuffer.toString();
    return ciphertext;