Apache Codec 库提供了一个十六进制工具类 org.apache.commons.codec.binary.Hex,使用它可以非常方便的将十六进制字符串转换字节数组,或者将字节数组转换成十六进制字符串。
byte[] encode(byte[] array)
按照顺序将字节数组转换为表示每个字节十六进制值的字符的字节数组。
byte[] decode(byte[] array)
将表示十六进制值的字符字节数组转换为这些值的字节数组。
示例代码
使用 encode 和 decode 方法简单实现十六进制转换,代码如下:
package com.huangx.codec;
import org.apache.commons.codec.binary.Hex;
import java.nio.ByteBuffer;
public class HexDemo2 {
public static void main(String[] args) throws Exception {
Hex hex = new Hex();
String str = "hello";
String hexStr = "68656c6c6f";
// 将 “hello” 字符串字节数组使用十六进制表示
byte[] bytes = hex.encode(str.getBytes());
System.out.println(new String(bytes)); // 68656c6c6f
// 将 “hello” 字符串字节数组使用十六进制表示
ByteBuffer byteBuffer = ByteBuffer.allocate(str.getBytes().length);
byteBuffer.put(str.getBytes());
byteBuffer.flip();
byte[] bytes2 = hex.encode(byteBuffer);
System.out.println(new String(bytes2));
// 将十六进制字符串解析成字节数组
byte[] result = hex.decode(hexStr.getBytes());
System.out.println(new String(result)); // hello
// 将十六进制字符串解析成字节数组
ByteBuffer byteBuffer1 = ByteBuffer.allocate(hexStr.getBytes().length);
byteBuffer1.put(hexStr.getBytes());
byteBuffer1.flip();
byte[] result2 = hex.decode(byteBuffer1);
System.out.println(new String(result2));
}
}运行上面程序,输出结果:
68656c6c6f
68656c6c6f
hello
hellochar[] encodeHex(byte[] data)
按顺序将字节数组转换为表示每个字节十六进制值的字符数组。
byte[] decodeHex(char[] data)
将表示十六进制值的字符数组转换为这些值的字节数组。
示例代码
下面实例将使用静态 encodeHex 和 decodeHex 方法快速对十六进制进行转换,代码如下:
package com.huangx.codec;
import org.apache.commons.codec.binary.Hex;
public class HexDemo3 {
public static void main(String[] args) throws Exception {
String str = "hello";
String hexStr = "68656c6c6f";
// 将 “hello” 字符串字节数组使用十六进制表示
System.out.println(new String(Hex.encodeHex(str.getBytes())));
// 将 “hello” 字符串字节数组使用十六进制表示
System.out.println(new String(Hex.decodeHex(hexStr.toCharArray())));
}
}运行上面程序,输出结果:
68656c6c6f
hello