Python 3 Convert String to Hex Bytes

吃可爱长大的小学妹 提交于 2019-12-26 18:56:11

问题


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?


回答1:


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'


来源:https://stackoverflow.com/questions/48915590/python-3-convert-string-to-hex-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!