当前位置 : 主页 > 编程语言 > java >

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

来源:互联网 收集:自由互联 发布时间:2023-09-03
(目录) commons-codec 文档 https://commons.apache.org/proper/commons-codec/ https://mvnrepository.com/artifact/commons-codec/commons-codec 坐标 dependency groupIdcommons-codec/groupId artifactIdcommons-codec/artifactId version1.15/vers

(目录)

commons-codec

文档

  • https://commons.apache.org/proper/commons-codec/
  • https://mvnrepository.com/artifact/commons-codec/commons-codec

坐标

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

byte数组转为16进制字符串

String hex = Hex.encodeHexString("123".getBytes());
System.out.println(hex);
// 313233

16进制字符串转为byte数组

byte[] src = Hex.decodeHex("313233");
System.out.println(new String(src));
// 123

完整代码

package com.example.demo;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.junit.Test;

public class TestCodec {

    @Test
    public void encode(){
        String hex = Hex.encodeHexString("123".getBytes());
        System.out.println(hex);
        // 313233
    }

    @Test
    public void decode() throws DecoderException {
        byte[] src = Hex.decodeHex("313233");
        System.out.println(new String(src));
        // 123
    }
}

实现原理

/**
* Hex类 该类用来对数据处理16进制的转换。
 */
public static class Hex {

    /*
     * 16进制数字字符集
     */
    private static final char[] HEX = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'
    };


    public static byte[] decode(CharSequence s) {
        int nChars = s.length();
        if (nChars % 2 != 0) {
            throw new IllegalArgumentException("16进制数据错误");
        }
        byte[] result = new byte[nChars / 2];
        for (int i = 0; i < nChars; i += 2) {
            int msb = Character.digit(s.charAt(i), 16);
            int lsb = Character.digit(s.charAt(i + 1), 16);
            if (msb < 0 || lsb < 0) {
                throw new IllegalArgumentException(
                        "Detected a Non-hex character at " + (i + 1) + " or " + (i + 2) + " position");
            }
            result[i / 2] = (byte) ((msb << 4) | lsb);
        }
        return result;
    }

    /*
     * 将字符串编码成16进制数字,适用于所有字符(包括中文)
     * 0x表示:16进制
     */
    public static String encode(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0, length = buf.length; i < length; i++) {
            // 高4位
            // 0xF0 1111 0000
            // 97=> 0110 0001
            //  &=> 0110 0000
            // >>> 4 =>0000 0110 == 6
            // =HEX[6] = 6

            // 低4位
            // 0x0F 0000 1111
            // 97=> 0110 0001
            // & => 0000 0001 == 1
            // =HEX[1] = 1

            sb.append(HEX[(buf[i] & 0xF0) >>> 4])
                    .append(HEX[buf[i] & 0x0F]); // 0x 0000 1111
        }
        return sb.toString();
    }
}

封装StringUtil 类

package com.example.demo.utils;

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

public class StringUtil {
    /**
     * 字符串转16进制
     * @param data
     * @return
     */
    public static String stringToHex(String data) {
        return Hex.encodeHexString(data.getBytes());
    }

    /**
     * 16进制转字符串
     * @param hex
     * @return
     */
    public static String hexToString(String hex) {
        try {
            return new String(Hex.decodeHex(hex));
        } catch (DecoderException e) {
            throw new RuntimeException(e);
        }
    }
}

参考

  • 程序员的福音 - Apache Commons Codec
【文章出处:抗攻击防御ddos http://www.558idc.com/krgf.html 复制请保留原URL】
网友评论