首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java/Android 十六進制字符串轉 byte[] 完整工具類

     編輯:程式設計綜合問答

場景

從 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}

Android 專項優化

  • 避免頻繁創建 StringBuilder,可複用 ThreadLocal 緩衝區。
  • 大數據量傳輸時,直接操作 ByteBuffer 避免中間數組拷貝。
  • 使用 android.util.Base64 進行 Base64 編碼傳輸,比 Hex 節省 33% 帶寬。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved