将十六进制转换为二进制,Android Studio,Java

问题描述 投票:0回答:1

我想在Android Studio中将像这样的十六进制代码转换为二进制,以进行蓝牙通信

这是原始的十六进制,以字符串形式出现。字符串十六进制=“ AA 06 00 5A 66 02 5B 02 5B 02 13 17 81 02 1C E7 77”;

期望结果=字节[]

我已经习惯于手动将此类字符先转换为char。0xAA,0x06,0x00,0x5A,0x66,0x02,0x5B,0x02,0x5B,0x02,0x13,0x17,0x81,0x02,0x1C,0xE7,0x77

我想从字符串十六进制=“ AA 06 00 5A 66 02 5B 02 5B 02 13 17 81 02 1C E7 77”;对此char [] patout = {0xAA,0x06,0x00,0x5A,0x66,0x02,0x5B,0x02,0x5B,0x02,0x13,0x17,0x81,0x02,0x1C,0xE7,0x77};

或直接转换为byte []。

java android binary char hex
1个回答
0
投票

您可以尝试以下方法:

public static byte[] hexStringToByteArray(String s) {
    s = s.replaceAll("\\s","")
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}
© www.soinside.com 2019 - 2024. All rights reserved.