java - java中的Apache通用编解码器从字符串到十六进制,反之亦然

标签 java string hex apache-commons-codec

我正在尝试以十六进制编码字符串,然后再次将其转换为字符串。为此,我使用 apache 通用编解码器。我特别定义了以下方法:

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
public String toHex(byte[] byteArray){

    return Hex.encodeHexString(byteArray);    

}

public byte[]  fromHex(String hexString){

    byte[] array = null;

    try {
        array = Hex.decodeHex(hexString.toCharArray());
    } catch (DecoderException ex) {
        Logger.getLogger(SecureHash.class.getName()).log(Level.SEVERE, null, ex);
    }

    return array;

}

奇怪的是,我在转换回来时没有得到相同的初始字符串。更奇怪的是,我得到的字节数组,它与字符串的初始字节数组不同。 我编写的小测试程序如下:

    String uno = "uno";
    byte[] uno_bytes = uno.getBytes();

    System.out.println(uno);
    System.out.println(uno_bytes);

    toHex(uno_bytes);
    System.out.println(hexed);

    byte [] arr = fromHex(hexed);
    System.out.println(arr.toString());

输出示例如下:

uno            #initial string
[B@1afe17b     #byte array of the initial string
756e6f         #string representation of the hex 
[B@34d46a      #byte array of the recovered string

还有另一个奇怪的行为。字节数组([B@1afe17b)不是固定的,但在代码的运行过程中有所不同,但我不明白为什么。

最佳答案

当您打印字节数组时,toString() 表示形式不包含数组的内容。相反,它包含一个类型指示符([B 表示字节数组)和哈希码。对于两个不同的字节数组,即使它们包含相同的内容,哈希码也会不同。请参阅Object.toString()Object.hashCode()欲了解更多信息。

相反,您可能想比较数组是否相等,使用:

System.out.println("Arrays equal: " + Arrays.equals(uno_bytes, arr));

关于java - java中的Apache通用编解码器从字符串到十六进制,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19907716/

相关文章:

C++/C : Prepend length to Char[] in bytes (binary/hex)

java - 我可以使用 Guava 的 ComparisonChain 以特殊方式处理 null 字段吗?

java 。如何在每个第 n 个空格上拆分具有多个空格的字符串?

c - 按字母顺序排列二维数组

ios - 如何从 iOS 中的 Url 获取特定值 - Swift 3

python - 将字符串中的十六进制字符附加到字符串

excel - 在 Excel 中将 HEX 转换为 RGB

java - Android:从应用程序执行二进制文件

java - 需要为SSL配置Tomcat 7

java - Graphics2D JPanel 显示但按钮不显示?