[英]How to convert byte to hex?
I am needing to send some data over serial but before I send, I need to calculate the checksum using modulo 256. I can work out the checksum and display it as a hex value (in this case the checksum is 0xb3
) but it displays it as 0xb3
but I need it to be \xb3
as I am sending other messages before it.我需要通过串行发送一些数据,但在发送之前,我需要使用模 256 计算校验和。我可以计算出校验和并将其显示为十六进制值(在这种情况下校验和为0xb3
)但它显示它作为0xb3
但我需要它是\xb3
因为我在它之前发送其他消息。
I have tried encoding, bytes and bytearray, but can not get it to send the hexadecimal value.我已经尝试过编码、字节和字节数组,但无法让它发送十六进制值。 It sends '0xb3'
as a string.它将'0xb3'
作为字符串发送。
def calculate_csum(message):
message = b'\x60\x08\x46\x52\x41\x50\x5a\x45\x52\x31' #just temp
j = 0
for i in message:
j = j + i
csum = hex(j % 256)
csum = csum.encode("ascii")
print(csum)
full_string = message + csum
print (full_string)
return csum
The output of the full string is b'\x08FRAPZER10xb3'
but if I hardcode it with b'\x60\x08\x46\x52\x41\x50\x5a\x45\x52\x31\xb3'
I get b'\x08FRAPZER1\xb3'
it works, so I need to drop the 0xb3
and replace it with \xb3
.完整字符串的 output 是b'\x08FRAPZER10xb3'
但如果我用b'\x60\x08\x46\x52\x41\x50\x5a\x45\x52\x31\xb3'
对其进行硬编码,我会得到b'\x08FRAPZER1\xb3'
它可以工作,所以我需要删除0xb3
并将其替换为\xb3
。
No need to go through gyrations to convert csum
to a string then back to a byte string, you want it as a single byte in the first place.无需 go 通过旋转将csum
转换为字符串然后再转换回字节字符串,您首先希望它作为单个字节。
csum = bytes([j % 256])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.