import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* HEX字符串與字節碼(字符串)轉換工具
*/
public class HexUtils {
public static void main(String[] args) throws Exception {
test("a");//編碼前【a】編碼后【61】解碼后【a】
test("A");//編碼前【A】編碼后【41】解碼后【A】
test("1");//編碼前【1】編碼后【31】解碼后【1】
test("白");//編碼前【白】編碼后【E799BD】解碼后【白】
test("白乾濤");//編碼前【白乾濤】編碼后【E799BDE4B9BEE6B69B】解碼后【白乾濤】
System.out.println(URLEncoder.encode("白乾濤", "UTF-8"));//和上述編碼結果一致【%E7%99%BD%E4%B9%BE%E6%B6%9B】
System.out.println(encodeHex("白乾濤".getBytes("UTF-8")));//使用apache的工具類編碼和上述編碼結果一致【e799bde4b9bee6b69b】
System.out.println(new String(decodeHex("e799bde4b9bee6b69b".toCharArray()), "UTF-8"));
}
private static void test(String input) throws UnsupportedEncodingException {
String charsetName = "UTF-8";
System.out.print("編碼前【" + input + "】");
System.out.print("編碼后【" + str2HexStr(input, charsetName) + "】");
System.out.println("解碼后【" + hexStr2Str(str2HexStr2(input, charsetName), charsetName) + "】");
}
//******************************************************************************************
// 參數或返回值為字符串
//******************************************************************************************
/**
* 將原始字符串轉換成16進制字符串【方法一】
*/
public static String str2HexStr(String input, String charsetName) throws UnsupportedEncodingException {
byte buf[] = input.getBytes(charsetName);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
//以十六進制(基數 16)無符號整數形式返回一個整數參數的字符串表示形式。
//如果參數為負,那么無符號整數值為參數加上 2^32;否則等於該參數。將該值轉換為十六進制(基數 16)的無前導 0 的 ASCII 數字字符串。
//如果無符號數的大小值為零,則用一個零字符 '0' (’\u0030’) 表示它;否則,無符號數大小的表示形式中的第一個字符將不是零字符。
//用以下字符作為十六進制數字【0123456789abcdef】。這些字符的范圍是從【'\u0030' 到 '\u0039'】和從【'\u0061' 到 '\u0066'】。
String hex = Integer.toHexString(buf[i] & 0xFF);//其實核心也就這一樣代碼
if (hex.length() == 1) hex = '0' + hex;
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 將原始字符串轉換成16進制字符串【方法二】
*/
public static String str2HexStr2(String str, String charsetName) throws UnsupportedEncodingException {
byte[] bs = str.getBytes(charsetName);
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0, bit; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString();
}
/**
* 將16進制字符串轉換為原始字符串
*/
public static String hexStr2Str(String hexStr, String charsetName) throws UnsupportedEncodingException {
if (hexStr.length() < 1) return null;
byte[] hexbytes = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
hexbytes[i] = (byte) (high * 16 + low);
}
return new String(hexbytes, charsetName);
}
//******************************************************************************************
// 參數或返回值為字節數組
//******************************************************************************************
/**
* 將二進制轉換成16進制
*/
public static String encode(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) hex = '0' + hex;
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 將16進制轉換為二進制(服務端)
*/
public static byte[] deocde(String hexStr) {
if (hexStr.length() < 1) return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
//******************************************************************************************
// org.apache.commons.codec.binary.Hex的實現方式
//******************************************************************************************
private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static char[] encodeHex(byte[] data) {
int l = data.length;
char[] out = new char[l << 1];
int i = 0;
for (int j = 0; i < l; i++) {
out[(j++)] = DIGITS[((0xF0 & data[i]) >>> 4)];
out[(j++)] = DIGITS[(0xF & data[i])];
}
return out;
}
public static byte[] decodeHex(char[] data) throws Exception {
int len = data.length;
if ((len & 0x1) != 0) throw new Exception("Odd number of characters.");
byte[] out = new byte[len >> 1];
int i = 0;
for (int j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f |= toDigit(data[j], j);
j++;
out[i] = ((byte) (f & 0xFF));
}
return out;
}
private static int toDigit(char ch, int index) throws Exception {
int digit = Character.digit(ch, 16);
if (digit == -1) throw new Exception("Illegal hexadecimal charcter " + ch + " at index " + index);
return digit;
}
}