2

我最近在寻找一种将字节数组转换为十六进制字符串的编码。一方面,我发现以下内容:如何将以下程序的十六进制转换为字节?

我已经尝试过这个:

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));
    } 

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

4

1 回答 1

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;
于 2013-03-31T03:11:45.180 回答