【问题标题】:Can someone explain the conversion from byte array to hexadecimal string in java有人可以解释java中从字节数组到十六进制字符串的转换吗
【发布时间】:2013-03-31 02:50:46
【问题描述】:

我最近在寻找一种将字节数组转换为十六进制字符串的编码。 一方面,我发现了以下内容: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));
    } 

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

【问题讨论】:

    标签: java arrays hex byte


    【解决方案1】:
    // 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;
    

    【讨论】:

    • 感谢您的帮助,但我仍然对解码的子字符串有点困惑。 String substr = message.substring(i, i+2);
    • 只解码编码的反向。它每次获取2个字符并将其解析为半径16整数==>转换为字节==>将其保存到字节数组“字节”中。出于与上述编码相同的原因,但解码需要恰好长度/2 来保存所有字节。
    猜你喜欢
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 2014-03-10
    相关资源
    最近更新 更多