简体   繁体   中英

How do I decode radar data read by Python/socket like b'\x08\x00\x00\x00' to numbers

I'm developing a Python3 program to process data from radar. In general, radar send data(hex numbers) to a port of my computer and I use socket to listen that port. And use code below to recive 4 bytes of data.

data = connection.recv(4)
print(data)

When testing my programm, radar send 08 00 00 01 and program print b'\\x08\\x00\\x00\\x01' . I understand the '\\x' means that the next to characters is a hex number, but I want to get numbers like [08, 00, 00, 01] or a normal string from it. Tried the most obvious way:

strData = data.decode()
print(strData.split('\x'))

Failed with SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \\xXX escape .

And situation goes worse if radar send 08 0D 00 00 , print(data) will print b'\\x08\\r\\x00\\x00' , which makes me realized that string operations can not handle this problem.

So, what is the right way to convert bytes like b'\\x08\\x00\\x00\\x01' to numbers like 08 00 00 01 .

String encoding drives me carzy -.- Although I am using Python3, solutions in Python2.7 is OK as well. Thanks in advance.

I guess you already get the binary data. If you really want the hex-representation as a string, this Answer to similar question could help you.

If you would like to interpreted the data as for example a float, struct could be used

import struct
x = struct.unpack('f',data)

For this specific case - you have a string of bytes, and you want to convert each byte to its integer equivalent - you can convert the bytestring directly to a list.

>>> bs = b'\x08\x00\x00\x01'
>>> ints = list(bs)
>>> ints
[8, 0, 0, 1]

This works because

bytes objects actually behave like immutable sequences of integer

so

[For] a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

(Quotations from the docs for the bytes type).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM