我正在尝试以十六进制编码字符串,然后再次将其转换为字符串。为此,我使用 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/