Java Code數組
public class Convert{ public static void main(String args[]) { String sHex = "00 B6 00 02 0A 28"; // 輸入十六進制字符串 sHex = sHex.replace(" ", ""); // 去掉空格 byte[] bytes = hexStringToBytes(sHex); // 十六進制轉字節數組 for (byte b : bytes) { System.out.print(b + " "); // 字節數組逐個打印出來 } } /** 十六進制轉換成字節數組 */ private static byte[] hexStringToBytes(String hexString) { if (hexString == null || hexString.equals("")) { return null; } hexString = hexString.toUpperCase(); // 十六進制轉大寫字母 int length = hexString.length() / 2; // 獲取十六進制的長度,2個字符爲一個十六進制 char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return d; } /** char轉byte */ private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); } }
輸出結果:0 -74 0 2 10 40spa