import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Hex; public class Example { /** * 將普通字符串轉換成Hex編碼字符串 * * @param dataCoding 編碼格式,15表示GBK編碼,8表示UnicodeBigUnmarked編碼,0表示ISO8859-1編碼 * @param realStr 普通字符串 * @return Hex編碼字符串 * @throws UnsupportedEncodingException */ public static String encodeHexStr(int dataCoding, String realStr) { String hexStr = null; if (realStr != null) { try { if (dataCoding == 15) { hexStr = new String(Hex.encodeHex(realStr.getBytes("GBK"))); } else if ((dataCoding & 0x0C) == 0x08) { hexStr = new String(Hex.encodeHex(realStr.getBytes("UnicodeBigUnmarked"))); } else { hexStr = new String(Hex.encodeHex(realStr.getBytes("ISO8859-1"))); } } catch (UnsupportedEncodingException e) { System.out.println(e.toString()); } } return hexStr; } /** * 將Hex編碼字符串轉換成普通字符串 * * @param dataCoding 反編碼格式,15表示GBK編碼,8表示UnicodeBigUnmarked編碼,0表示ISO8859-1編碼 * @param hexStr Hex編碼字符串 * @return 普通字符串 */ public static String decodeHexStr(int dataCoding, String hexStr) { String realStr = null; try { if (hexStr != null) { if (dataCoding == 15) { realStr = new String(Hex.decodeHex(hexStr.toCharArray()), "GBK"); } else if ((dataCoding & 0x0C) == 0x08) { realStr = new String(Hex.decodeHex(hexStr.toCharArray()), "UnicodeBigUnmarked"); } else { realStr = new String(Hex.decodeHex(hexStr.toCharArray()), "ISO8859-1"); } } } catch (Exception e) { System.out.println(e.toString()); } return realStr; } }