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

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

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

最佳答案

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

关于java - 有人可以解释在 java 中从字节数组到十六进制字符串的转换吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15725845/

相关文章:

java - 2 的十六进制数补码在 Java 中转为十进制

java - 线程数组的最佳实践 (java)

java - 如何对十六进制字符串进行base-64编码

c - C中十六进制字符串到int的转换

java - 如何在 Intellij 中调试多线程 java 应用程序时查看多个堆栈跟踪?

java - 来自文本文件的数据评估

C# - 获取字符串中的整数字节数组

java - 为什么我在使用 Mapreduce 时得到了一个困惑的结果

java - Eclipse Maven : SLF4J: Class path contains multiple SLF4J bindings

java - 运行内存密集型 Java 应用程序后操作系统变慢的原因是什么?