I gradually master Python and write a program for communicating with the AVR controller via bluetooth.

From the socket, I receive data as a string of bytes of this type b'\xb1\xaa\xab\xac\xad\xae\xaf' .

Since I am writing my own protocol and working with different data types (I send them from MK not in symbolic form), I break the line into parts, for example: b'\xb1' , b\xaa\xab' and b\xac\xad\xae\xaf' , that is, a one-byte int, a two-byte int, and a four-byte int, with which there are no problems.

The main task is to convert these byte sequences into original numbers. One-byte int quite turns out to transform as:

 In [64]: line = b'\t\xaa\xab\xac\xad\xae\xaf' In [65]: line [0] Out[65]: 9 In [72]: a = line [0] In [73]: a Out[73]: 9 In [74]: a += 1 In [75]: a Out[75]: 10 

But here the method of converting to the number of two or more buy is unknown to me As a result of the search more confused. And so, the question is: how do you have byte strings of the form b\xaa\xab' and b\xac\xad\xae\xaf' in the source data to bring them to an integer data type?

  • what version of python? - nick_gabpe
  • Spyder, Python 3.5 - Alexey Simakov

2 answers 2

To convert bytes to an integer in Python 3 regardless of the number of bytes:

 >>> int.from_bytes(b'\xb1', 'big') 177 >>> int.from_bytes(b'\xaa\xab', 'big') 43691 >>> int.from_bytes(b'\xac\xad\xae\xaf', 'big') 2897063599 >>> int.from_bytes(b'\xac\xad\xae\xaf', 'big', signed=True) -1397903697 >>> int.from_bytes(b'\xac\xad\xae\xaf', 'little', signed=True) -1347506772 >>> int.from_bytes(b'\xac\xad\xae\xaf', 'little') 2947460524 

If there is a lot of data of the same type, you can array.array , numpy.array to save memory and speed vector operations.

If there is a framing structure, then you can read the data using struct.Struct , ctypes.Structure (for a struct from C) .

  • Spasobo, earned! And yes, the data arrays in my area are 3.5 kilobytes / second. - Alexey Simakov

Look in the direction of the struct module, it is just for these tasks. In your case:

 import struct line = b'\xaa\xab\xac\xad\xae\xaf' format = '<hi' print(struct.unpack(format, line)) (-21590, -1347506772) 

For simplicity, I threw out the line \ t line, but you can also parse the line with it:

 import struct line = b'\t\xaa\xab\xac\xad\xae\xaf' format = '<Bhi' print(struct.unpack(format, line)) (9, -21590, -1347506772) 
  • An interesting approach. That is, we set the mask for the parser and it unpacks the data itself ... No wonder I switched to python! - Alexey Simakov