最近開發任務是和攝像機彩屏進行通訊。在進行串口通訊時需要傳輸byte數組,而當內容為中文時需要指定GBK編碼,否則會亂碼。所以總結下這兩個java方法。
1 /** 2 * 將字符串轉為指定編碼的16進制 3 * 4 * @param str 5 * @return 6 */ 7 public static String encode(String str) throws Exception { 8 String hexString = "0123456789ABCDEF"; 9 //根據編碼獲取字節數組 10 byte[] bytes = str.getBytes("GBK"); 11 StringBuilder sb = new StringBuilder(bytes.length * 2); 12 //將字節數組中每個字節拆解成2位16進制整數 13 for (int i = 0; i < bytes.length; i++) { 14 sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4)); 15 sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0)); 16 } 17 return sb.toString(); 18 }
1 /** 2 * 將16進制字符串轉換為byte[] 3 * 4 * @param str 5 * @return 6 */ 7 public static byte[] toBytes(String str) { 8 if (str == null || str.trim().equals("")) { 9 return new byte[0]; 10 } 11 12 byte[] bytes = new byte[str.length() / 2]; 13 for (int i = 0; i < str.length() / 2; i++) { 14 String subStr = str.substring(i * 2, i * 2 + 2); 15 bytes[i] = (byte) Integer.parseInt(subStr, 16); 16 } 17 18 return bytes; 19 }