java byte[]與十六進制字符串相互轉換

前言:我們經常在加密或者進行數字簽名的時候,需要將字節數組(byte[])與十六進制表示的字符串之間進行相互轉換。本篇文章介紹幾種將字節數組轉換爲十六進制字符串的幾種方法,以及將十六進制字符串轉換爲字節數組。

直接上代碼,如下:

package string;

import java.util.Arrays;

/**
 * byte[]與16進制字符串相互轉換
 * 
 * @date:2017年4月10日 下午11:04:27    
 */
public class BytesHexStrTranslate {

    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 bytesToHexFun1(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 bytesToHexFun2(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 bytesToHexFun3(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;
    }

    public static void main(String[] args) throws Exception {
        byte[] bytes = "測試".getBytes("utf-8");
        System.out.println("字節數組爲:" + Arrays.toString(bytes));
        System.out.println("方法一:" + bytesToHexFun1(bytes));
        System.out.println("方法二:" + bytesToHexFun2(bytes));
        System.out.println("方法三:" + bytesToHexFun3(bytes));

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

        String str = "e6b58be8af95";
        System.out.println("轉換後的字節數組:" + Arrays.toString(toBytes(str)));
        System.out.println(new String(toBytes(str), "utf-8"));
    }

}

運行結果如下:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章