Python 3 将字符串转换为十六进制字节 [英] Python 3 Convert String to Hex Bytes
问题描述
我需要将一个简单的字符串转换为一个使用十六进制表示的字节数组,就像那个站点一样:http://string-functions.com/string-hex.aspx
这个字符串然后使用 python 通过蓝牙发送,arduino 像这样读取单个字节:
char buff[1000];int i = 0;int typeByte = serial->read();int data = serial->read();而(真){如果(数据== -1)继续;如果(数据 == 254 || 数据 == 10)中断;buff[i++] = 数据;数据=串行->读取();延迟(10);}字符串缓冲区(buff);if(buffer.startsWith("AUTH")){做东西();}
然后将它们存储在 char[] 数组中并用于与命令名称进行比较.
这是我在 Python 项目中使用的代码(消息是一个字符串,例如AUTH")
self.bluetooth_socket.send(b"\x01" + message.encode('ascii') + b"\x10")
这是 arduino 收到的:
01 65 85 84 72 16
但它应该是这样的:
01 41 55 54 48 10
我知道第二个字节数组基本上是第一个以十六进制表示的数组 - 我将如何实现?
是的,在你发送的第一个数组中的 ascii 值.在 python3 中获取十六进制值:
<预><代码>>>>导入编解码器>>>codecs.encode(message.encode("ascii"), "hex")b'41555448'I need to convert a simple string to a byte array which uses hex representation, just like that site: http://string-functions.com/string-hex.aspx
This string then gets send via bluetooth using python and the arduino reads the individual bytes like this:
char buff[1000];
int i =0;
int typeByte = serial->read();
int data = serial->read();
while (true) {
if (data == -1) continue;
if (data == 254 || data == 10) break;
buff[i++] = data;
data = serial->read();
delay(10);
}
String buffer(buff);
if(buffer.startsWith("AUTH")){
dostuff();
}
Those are then stored in a char[] array and used for comparison with a command name.
This is the code I am using in the Python Project (message is a string for example "AUTH")
self.bluetooth_socket.send(b"\x01" + message.encode('ascii') + b"\x10")
This is what the arduino receives:
01 65 85 84 72 16
But it should look like that:
01 41 55 54 48 10
I know that the second byte array is basically the first one just in hex representation - how would I achieve that?
Yeah, in the first array you sent the ascii values. To get the hex values in python3:
>>> import codecs
>>> codecs.encode(message.encode("ascii"), "hex")
b'41555448'
这篇关于Python 3 将字符串转换为十六进制字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!