從 SD 卡讀取 "0x03 0x04 0x05" 格式字符串,需轉為 byte[] {0x03, 0x04, 0x05} 供串口/藍牙發送。
public class HexUtil {
/** 將 "0x03 0x04" 或 "0304" 或 "03 04" 轉為 byte[] */
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.isEmpty()) return null;
// 移除 0x/0X 前綴、空格、換行
String cleaned = hexString.toUpperCase().replace("0X", "").replaceAll("\\s+", "");
int len = cleaned.length();
if (len % 2 != 0) throw new IllegalArgumentException("十六進制字符串長度必須為偶數");
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) Integer.parseInt(cleaned.substring(i, i + 2), 16);
}
return data;
}
/** byte[] 轉 "03 04 05" 格式字符串 */
public static String bytesToHexString(byte[] bytes, String separator) {
if (bytes == null) return "";
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int i = 0; i < bytes.length; i++) {
if (i > 0) sb.append(separator);
sb.append(String.format("%02X", bytes[i]));
}
return sb.toString();
}
}
String input = "0x03 0x04 0x05";
byte[] bytes = HexUtil.hexStringToBytes(input);
// bytes = {3, 4, 5}
String output = HexUtil.bytesToHexString(bytes, " ");
// output = "03 04 05"
| 輸入 | 處理結果 |
|---|---|
null / "" | 返回 null / 空數組 |
"0xGG" | 拋出 NumberFormatException |
"03 04 0" | 拋出長度異常 |
"0x030x04" | 正常解析為 {3,4} |
StringBuilder,可複用 ThreadLocal 緩衝區。ByteBuffer 避免中間數組拷貝。android.util.Base64 進行 Base64 編碼傳輸,比 Hex 節省 33% 帶寬。