View Javadoc
1   package com.zone.weixin4j.util;
2   
3   /**
4    * Hex工具类
5    * 
6    * @className HexUtil
7    * @author jinyu(foxinmy@gmail.com)
8    * @date 2015年5月17日
9    * @since JDK 1.6
10   * @see
11   */
12  public final class HexUtil {
13  	/**
14  	 * Used to build output as Hex
15  	 */
16  	private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5',
17  			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
18  
19  	/**
20  	 * Used to build output as Hex
21  	 */
22  	private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5',
23  			'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
24  
25  	private static char[] encodeHex(final byte[] data, final char[] toDigits) {
26  		final int l = data.length;
27  		final char[] out = new char[l << 1];
28  		// two characters form the hex value.
29  		for (int i = 0, j = 0; i < l; i++) {
30  			out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
31  			out[j++] = toDigits[0x0F & data[i]];
32  		}
33  		return out;
34  	}
35  
36  	public static String encodeHexString(final byte[] data) {
37  		return new String(encodeHex(data, true));
38  	}
39  
40  	public static char[] encodeHex(final byte[] data, final boolean toLowerCase) {
41  		return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
42  	}
43  }