Java byte[ ]与十六进制字符串相互转换

很多时候我们需要将字节数组转化为16进制字符串来保存,在很多加密的场景中,例如保存密钥等都需要将 Byte[ ] 转换为 String 。因为 Byte[ ] ,除了写入文件或者以二进制的形式写入数据库以外,无法直接转为为字符串。而输入密钥等操作,却不可能直接让用户输入一长串的 Byte[ ] ,我们会让用户输入 String ,所以这种需求就出现了。

一、工具类

package com.it.keithxiaoy;

public class StringUtils {

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 方法一:
     * byte[] to hex string
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex1(byte[] bytes) {
        // 一个byte为8位,可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a = 0;
        int index = 0;
        for(byte b : bytes) { // 使用除与取余进行转换
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }

            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }

        return new String(buf);
    }

    /**
     * 方法二:
     * byte[] to hex string
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex2(byte[] bytes) {
        char[] buf = new char[bytes.length * 2];
        int index = 0;
        for(byte b : bytes) { // 利用位运算进行转换,可以看作方法一的变种
            buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
            buf[index++] = HEX_CHAR[b & 0xf];
        }

        return new String(buf);
    }

    /**
     * 方法三:
     * byte[] to hex string
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex3(byte[] bytes) {
        StringBuilder buf = new StringBuilder(bytes.length * 2);
        for(byte b : bytes) { // 使用String的format方法进行转换
            buf.append(String.format("%02x", new Integer(b & 0xff)));
        }

        return buf.toString();
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }
}

二、测试

package com.it.keithxiaoy;

import com.it.keithxiaoy.StringUtils;

import java.util.Arrays;

public class TestConvert {
    public static void main(String[] args) throws Exception {
        byte[] bytes = {(byte) 0x77, (byte) 0xa6, (byte) 0x89, (byte) 0x1e, (byte) 0xec, (byte) 0x7e, (byte) 0x3f, (byte) 0xb6, (byte) 0x94, (byte) 0xec, (byte) 0xc8, (byte) 0xed, (byte) 0xe6, (byte) 0xf3, (byte) 0x5d, (byte) 0xe8, (byte) 0x7f, (byte) 0xbe, (byte) 0x50, (byte) 0x65, (byte) 0x56, (byte) 0xf1, (byte) 0x2e, (byte) 0x4b, (byte) 0x9c, (byte) 0xca, (byte) 0x2d, (byte) 0xd2, (byte) 0x5c, (byte) 0x89, (byte) 0x09, (byte) 0x25};
        System.out.println("字节数组为:" + Arrays.toString(bytes));
        System.out.println("方法一:" + StringUtils.bytesToHex1(bytes));
        System.out.println("方法二:" + StringUtils.bytesToHex2(bytes));
        System.out.println("方法三:" + StringUtils.bytesToHex3(bytes));

        System.out.println("==================================");

        String str = "77a6891eec7e3fb694ecc8ede6f35de87fbe506556f12e4b9cca2dd25c890925";
        System.out.println("转换后的字节数组:" + Arrays.toString(StringUtils.toBytes(str)));
        System.out.println(new String(StringUtils.toBytes(str), "utf-8"));
    }
}

三、结果

字节数组为:[119, -90, -119, 30, -20, 126, 63, -74, -108, -20, -56, -19, -26, -13, 93, -24, 127, -66, 80, 101, 86, -15, 46, 75, -100, -54, 45, -46, 92, -119, 9, 37]
方法一:77a6891eec7e3fb694ecc8ede6f35de87fbe506556f12e4b9cca2dd25c890925
方法二:77a6891eec7e3fb694ecc8ede6f35de87fbe506556f12e4b9cca2dd25c890925
方法三:77a6891eec7e3fb694ecc8ede6f35de87fbe506556f12e4b9cca2dd25c890925
==================================
转换后的字节数组:[119, -90, -119, 30, -20, 126, 63, -74, -108, -20, -56, -19, -26, -13, 93, -24, 127, -66, 80, 101, 86, -15, 46, 75, -100, -54, 45, -46, 92, -119, 9, 37]
w���~?�������]��PeV�.K��-�\� %

本文原创发布于微信公众号「NoBug」,编程、思维、成长、正能量,关注并回复「编程」、「阅读」、「Java」、「Python」等关键字获取免费学习资料

不要给自己的人生设限

猜你喜欢

转载自blog.csdn.net/xiaoy_yan/article/details/81002312