Python 3将字符串转换为十六进制字节 [英] Python 3 Convert String to Hex Bytes
问题描述
我需要将一个简单的字符串转换为一个使用十六进制表示的字节数组,就像该站点一样:
http://string-functions.com/string-hex.aspx
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
然后这个字符串通过蓝牙使用python发送, arduino读取像这样的单个字节:
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();
}
然后将这些存储在char []数组中,并用于与命令名。
Those are then stored in a char[] array and used for comparison with a command name.
这是我在Python Project中使用的代码(消息是一个字符串,例如AUTH)
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")
这就是arduino收到的内容:
This is what the arduino receives:
01 65 85 84 72 16
但应该看起来像这样:
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?
推荐答案
是的,在第一个数组中,您发送了ascii值。
要获取python3中的十六进制值:
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屋!