python316进制_Python 3将字符串转换为十六进制字节

本文讨论如何将简单的字符串转换为十六进制表示的字节数组,以便通过蓝牙进行传输。在Python中,可以使用codecs库的encode方法将ASCII字符串转化为十六进制。在Arduino端,接收到的数据需要正确解析。文章提供了Python发送数据的代码示例,并对比了期望的和实际接收到的数据。问题在于原始发送的数据是ASCII值,而目标是十六进制表示。
摘要由CSDN通过智能技术生成

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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值