1

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.

sjakobi
  • 3,546
  • 1
  • 25
  • 43
Hongxu Jin
  • 817
  • 2
  • 9
  • 16
  • Do you want integers ``8, ...``, 2-character hex strings ``"08", ...``, or just the entire number, i.e. ``134217729``? – MisterMiyagi May 09 '19 at 16:20

2 Answers2

1

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)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Stefan
  • 66
  • 6
1

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).

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153