閱讀208 返回首頁    go 阿裏雲 go 技術社區[雲棲]


java中byte數組與十六進製字符串相互轉換

最近在做加密算法的研究和使用,經常會用到byte數組和十六進製字符串的轉換。之前對於此類問題我一般都是使用BigInteger這個類轉換一下算了,這樣為了看輸出不是亂碼。這其實都不是根本上的解決方案。

最簡單的轉換方法:

/**
 * @see 將byte[]數組轉換為String字符串
 * @author Herman.Xiong
 * @date 2014年5月5日 17:15:42
 * @param data byte數組
 * @return String 轉換後的字符串
 */
public static String byteToArray(byte[]data){
	String result="";
	for (int i = 0; i < data.length; i++) {
		result+=Integer.toHexString((data[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3);
	}
	return result;
}
我們看看java的byte[]數組的原理:

Java中byte用二進製表示占用8位,而我們知道16進製的每個字符需要用4位二進製位來表示。

所以我們就可以把每個byte轉換成兩個相應的16進製字符,即把byte的高4位和低4位分別轉換成相應的16進製字符H和L,並組合起來得到byte轉換到16進製字符串的結果new String(H) + new String(L)。

同理,相反的轉換也是將兩個16進製字符轉換成一個byte,原理同上。

根據以上原理,我們就可以將byte[] 數組轉換為16進製字符串了,當然也可以將16進製字符串轉換為byte[]數組了。

一下是代碼工具類:

package com.herman.test;

/**
 * @see byte數組與十六進製字符串互轉
 * @author Herman.Xiong
 * @date 2014年5月5日 17:00:01
 */
public class Hex {

	/**
	 * 用於建立十六進製字符的輸出的小寫字符數組
	 */
	private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * 用於建立十六進製字符的輸出的大寫字符數組
	 */
	private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	/**
	 * @see 將字節數組轉換為十六進製字符數組
	 * @author Herman.Xiong
	 * @date 2014年5月5日 17:06:52
	 * @param data byte[]
	 * @return 十六進製char[]
	 */
	public static char[] encodeHex(byte[] data) {
		return encodeHex(data, true);
	}

	/**
	 * @see 將字節數組轉換為十六進製字符數組
	 * @author Herman.Xiong
	 * @date 2014年5月5日 17:07:14
	 * @param data byte[]
	 * @param toLowerCase true傳換成小寫格式 ,false傳換成大寫格式
	 * @return 十六進製char[]
	 */
	public static char[] encodeHex(byte[] data, boolean toLowerCase) {
		return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
	}

	/**
	 * @see 將字節數組轉換為十六進製字符數組
	 * @author Herman.Xiong
	 * @date 2014年5月5日 17:07:31
	 * @param data byte[]
	 * @param toDigits 用於控製輸出的char[]
	 * @return 十六進製char[]
	 */
	protected static char[] encodeHex(byte[] data, char[] toDigits) {
		int l = data.length;
		char[] out = new char[l << 1];
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
			out[j++] = toDigits[0x0F & data[i]];
		}
		return out;
	}

	/**
	 * @see 將字節數組轉換為十六進製字符串
	 * @date 2014年5月5日 17:07:43
	 * @author Herman.Xiong
	 * @param data byte[]
	 * @return 十六進製String
	 */
	public static String encodeHexStr(byte[] data) {
		return encodeHexStr(data, true);
	}

	/**
	 * @see 將字節數組轉換為十六進製字符串
	 * @author Herman.Xiong
	 * @date 2014年5月5日 17:08:01
	 * @param data byte[]
	 * @param toLowerCase true 傳換成小寫格式 , false 傳換成大寫格式
	 * @return 十六進製String
	 */
	public static String encodeHexStr(byte[] data, boolean toLowerCase) {
		return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
	}

	/**
	 * @see 將字節數組轉換為十六進製字符串
	 * @author Herman.Xiong
	 * @date 2014年5月5日 17:08:15
	 * @param data byte[]
	 * @param toDigits 用於控製輸出的char[]
	 * @return 十六進製String
	 */
	protected static String encodeHexStr(byte[] data, char[] toDigits) {
		return new String(encodeHex(data, toDigits));
	}

	/**
	 * @see 將十六進製字符數組轉換為字節數組
	 * @author Herman.Xiong
	 * @date 2014年5月5日 17:08:28
	 * @param data 十六進製char[]
	 * @return byte[]
	 * @throws RuntimeException 如果源十六進製字符數組是一個奇怪的長度,將拋出運行時異常
	 */
	public static byte[] decodeHex(char[] data) {
		int len = data.length;
		if ((len & 0x01) != 0) {
			throw new RuntimeException("未知的字符");
		}
		byte[] out = new byte[len >> 1];
		for (int i = 0, j = 0; j < len; i++) {
			int f = toDigit(data[j], j) << 4;
			j++;
			f = f | toDigit(data[j], j);
			j++;
			out[i] = (byte) (f & 0xFF);
		}
		return out;
	}

	/**
	 * @see 將十六進製字符轉換成一個整數
	 * @author Herman.Xiong
	 * @date 2014年5月5日 17:08:46
	 * @param ch  十六進製char
	 * @param index 十六進製字符在字符數組中的位置
	 * @return 一個整數
	 * @throws RuntimeException 當ch不是一個合法的十六進製字符時,拋出運行時異常
	 */
	protected static int toDigit(char ch, int index) {
		int digit = Character.digit(ch, 16);
		if (digit == -1) {
			throw new RuntimeException("非法16進製字符 " + ch
					+ " 在索引 " + index);
		}
		return digit;
	}

	/**
	 * @see 將byte[]數組轉換為String字符串
	 * @author Herman.Xiong
	 * @date 2014年5月5日 17:15:42
	 * @param data byte數組
	 * @return String 轉換後的字符串
	 */
	public static String byteToArray(byte[]data){
		String result="";
		for (int i = 0; i < data.length; i++) {
			result+=Integer.toHexString((data[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3);
		}
		return result;
	}
	
	public static void main(String[] args) {
		String srcStr = "待轉換字符串";
		String encodeStr = encodeHexStr(srcStr.getBytes());
		String decodeStr = new String(decodeHex(encodeStr.toCharArray()));
		System.out.println("轉換前:" + srcStr);
		System.out.println("轉換後:" + encodeStr);
		System.out.println("還原後:" + decodeStr);
	}

}

運行後效果:



最後更新:2017-04-03 12:56:32

  上一篇:go Linux下Tomcat catalina.out自動歸檔,以及logrotate 配置詳解
  下一篇:go 破解手機輻射危害健康的流言