简体   繁体   English

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

[英]Can someone explain the conversion from byte array to hexadecimal string in java

I was recently looking for an encoding to convert the byte array to a hexadecimal string. 我最近在寻找一种将字节数组转换为十六进制字符串的编码。 For one, I found the following from: how to convert hex to byte for the following program? 首先,我发现以下内容: 如何将以下程序的十六进制转换为字节?

I have already tried this: 我已经尝试过了:

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;

for decoding: 用于解码:

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

but I dont kow how these algorithms work in detail, please can someone explain this? 但是我不知道这些算法如何详细工作,请有人可以解释一下吗?

// 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM