Apache Codec Hex工具类

本文将介绍 Apache Codec Hex 工具类的用法,使用该工具类可以将十六进制字符串转换成字节数组,也可将字节数组转换成十六进制字符串。

Apache Codec 库提供了一个十六进制工具类 org.apache.commons.codec.binary.Hex,使用它可以非常方便的将十六进制字符串转换字节数组,或者将字节数组转换成十六进制字符串。

encode(byte[] array) 和 decode(byte[] array)

  • 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
hello

encodeHex(byte[] data) 和 decodeHex(char[] data)

  • char[] 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
业精于勤,荒于嬉。——韩愈《进学解》
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号