Java:commons-codec实现byte数组和16进制字符串转换

在Java中,可以使用Apache的commons-codec库来实现byte数组和16进制字符串的转换。以下是一个简单的示例:

首先,确保你的项目中已经引入了commons-codec库。如果使用Maven,可以在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>
 

然后,可以使用Hex类来实现转换:

import org.apache.commons.codec.binary.Hex;

public class Main {
    public static void main(String[] args) {
        // byte数组转16进制字符串
        byte[] bytes = {10, 2, 15, 11};
        String hexString = Hex.encodeHexString(bytes);
        System.out.println(hexString);

        // 16进制字符串转byte数组
        try {
            byte[] bytesFromHex = Hex.decodeHex(hexString);
            for (byte b : bytesFromHex) {
                System.out.println(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
posted @ 2025-06-11 09:21  kite1990  阅读(70)  评论(0)    收藏  举报