測試代碼
package cn.java.codec.hex; public class Test { public static void main(String[] args) { String str = "test"; System.out.println("test string : "+str); String hexEncode = HexUtil.encode(str.getBytes()); System.out.println("HexUtil.encode Result : "+hexEncode); byte[] bytes = HexUtil.decode(hexEncode); System.out.println("HexUtil.decode Result : "+new String(bytes)); } }
輸出內容
test string : test HexUtil.encode Result : 74657374 HexUtil.decode Result : test
工具類
package cn.java.codec.hex; public class HexUtil { /** * 字節流轉成十六進制表示 */ public static String encode(byte[] src) { String strHex = ""; StringBuilder sb = new StringBuilder(""); for (int n = 0; n < src.length; n++) { strHex = Integer.toHexString(src[n] & 0xFF); sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每個字節由兩個字符表示,位數不夠,高位補0 } return sb.toString().trim(); } /** * 字符串轉成字節流 */ public static byte[] decode(String src) { int m = 0, n = 0; int byteLen = src.length() / 2; // 每兩個字符描述一個字節 byte[] ret = new byte[byteLen]; for (int i = 0; i < byteLen; i++) { m = i * 2 + 1; n = m + 1; int intVal = Integer.decode("0x" + src.substring(i * 2, m) + src.substring(m, n)); ret[i] = Byte.valueOf((byte)intVal); } return ret; } }