Apache Codec Hex十六进制转换

本文将介绍怎样利用Apache Codec的Hex类实现十六进制字符串转换成字节数组,或者将字节数组转换成十六进制字符串。

下面实例将介绍使用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 < hexStr.length(); 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:该方法将给定的字符串或字符数组解码成字节数组

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