java中十六进制编码与解码

java中十六进制编码与解码

一、简介

十六进制编码就是把二进制转换十六进制字符串,即是0-9,a-f。或者相反。实现就是将二进制流,每四位一组,进行编码。

二、代码实现

public class ByteHexMain {
    public static void main(String[] args) throws Exception {
        String source = "study hard and make progress everyday";
        System.out.println("source : "+source);

        String hexStr = bytes2HexStr(source.getBytes("utf8"));  //编码
        System.out.println("encode result : "+ hexStr);

        String rawSource = new String(hexStr2Bytes(hexStr),"utf8");  //解码
        System.out.println("decode result : "+rawSource);

    }

    //byte转为hex串
    static String bytes2HexStr(byte[] byteArr) {
        if (null == byteArr || byteArr.length < 1) return "";
        StringBuilder sb = new StringBuilder();
        for (byte t : byteArr) {
            if ((t & 0xF0) == 0) sb.append("0");
            sb.append(Integer.toHexString(t & 0xFF));  //t & 0xFF 操作是为去除Integer高位多余的符号位(java数据是用补码表示)
        }
        return sb.toString();
    }

    //hex串转为byte
    static byte[] hexStr2Bytes(String hexStr) {
        if (null == hexStr || hexStr.length() < 1) return null;

        int byteLen = hexStr.length() / 2;
        byte[] result = new byte[byteLen];
        char[] hexChar = hexStr.toCharArray();
        for(int i=0 ;i<byteLen;i++){
           result[i] = (byte)(Character.digit(hexChar[i*2],16)<<4 | Character.digit(hexChar[i*2+1],16));
        }
        return result;
    }
}

运行结果:

source : study hard and make progress everyday
encode result : 7374756479206861726420616e64206d616b652070726f6772657373206576657279646179
decode result : study hard and make progress everyday
发布了274 篇原创文章 · 获赞 95 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/chinabestchina/article/details/105212391
今日推荐