Apache通用java编解码器,从字符串到十六进制,反之亦然
我试图用十六进制编码一个字符串,然后再把它转换成字符串。为此,我使用apache通用编解码器。我特别定义了以下方法:Apache通用java编解码器,从字符串到十六进制,反之亦然,java,string,hex,apache-commons-codec,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
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
输出示例如下所示:
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
表示字节数组)和哈希代码。两个不同字节数组的哈希代码将不同,即使它们包含相同的内容。有关更多信息,请参阅和
相反,您可能希望使用以下方法比较数组是否相等:
System.out.println("Arrays equal: " + Arrays.equals(uno_bytes, arr));