下面实例将介绍使用Hex类将字节数组转换成十六进制字符串,然后再将十六进制字符串转换成字节数组。代码如下:import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import java.nio.ByteBuffer;
/**
* Apache Commons Codec 十六进制工具
*/
public class HexDemo {
public static void main(String[] args) {
byte[] bytes = "Hello World".getBytes();
String hexStr = "48656c6c6f20576f726c64";
// 创建字符数组
char[] chars = new char[hexStr.length()];
for(int i = 0; i
chars[i] = hexStr.charAt(i);
}
System.out.println("encodeHexString字节数组:" + Hex.encodeHexString(bytes));
System.out.println("encodeHexString字节数组:" + Hex.encodeHexString(bytes, false));
System.out.println("ByteBuffer参数:" + Hex.encodeHexString(ByteBuffer.wrap(bytes)));
System.out.println("ByteBuffer参数:" + Hex.encodeHexString(ByteBuffer.wrap(bytes), false));
try {
// 解析
System.out.println("decodeHex字符串参数:" + new String(Hex.decodeHex(hexStr)));
System.out.println("decodeHex字符数组参数:" + new String(Hex.decodeHex(chars)));
} catch (DecoderException e) {
e.printStackTrace();
}
}
}
Hex提供的方法有如下几类:encodingHexString:将字节数组或者ByteBuffer中的内容编码成十六进制字符串,允许控制十六进制的大小写。
encodeHex:该方法将字节数组或ByteBuffer中的内容编码成十六进制字符数组。
decodeHex:该方法将给定的字符串或字符数组解码成字节数组