字符串转hex
1 2 public static String toHex(String text) throws Exception { 3 4 //将字符串转为GB2312数组 5 byte[] arr = text.getBytes("GB2312"); 6 7 //将数组转为16进制字符串 8 String hexStr = ""; 9 for (int i = 0; i < arr.length; i++) { 10 String str = byteToHex(arr[i]); 11 hexStr = hexStr + str; 12 } 13 return hexStr; 14 } 15 16 public static String byteToHex(byte b) { 17 String hex = Integer.toHexString(b & 0xFF); 18 if (hex.length() < 2) { 19 hex = "0" + hex; 20 } 21 return hex; 22 } 23 24 25 public static String hexStrToStr(String hexStr) { 26 //能被16整除,肯定可以被2整除 27 byte[] array = new byte[hexStr.length() / 2]; 28 try { 29 for (int i = 0; i < array.length; i++) { 30 array[i] = (byte) (0xff & Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16)); 31 } 32 hexStr = new String(array, "GB2312"); 33 } catch (Exception e) { 34 e.printStackTrace(); 35 return ""; 36 } 37 return hexStr; 38 }
test
String toStr = LkFeeUtils.hexStrToStr("BEA9413132333435"); System.out.println(toStr); String hex = LkFeeUtils.toHex("京A12345"); System.out.println(hex.toUpperCase());