简体   繁体   English

在Python中,如何从套接字接收16位整数元组的数组?

[英]How to receive an array of 16-bit integer tuples from a socket, in Python?

My Python app needs to receive an array of 16-bit integer tuples from a C++ application. 我的Python应用程序需要从C ++应用程序接收一个16位整数元组数组。

The data consists of an array of 32-bit unsigned integers, where each integer represents an IQ complex number. 数据由32位无符号整数组成,其中每个整数代表IQ复数。 I and Q are each signed 16-bit numbers. I和Q均为带符号的16位数字。

The array size is constant (6000). 数组大小为常数(6000)。

The apps run on similar architectures so I don't need to worry about endianness. 这些应用程序在类似的架构上运行,因此我不必担心字节序。

Please suggest a Python code snippet to read the data from a socket into a list of IQ tuples. 请提出一个Python代码段,以从套接字将数据读取到IQ元组列表中。 (I know how to create and connect a socket). (我知道如何创建和连接套接字)。

Best regards 最好的祝福

David 大卫

You can use struct library in python is you have incoming data as hexadecimal bytes. 您可以在python中使用struct库,因为您输入的数据为十六进制字节。

Or if they are simple hexadecimal numbers then conversion is direct. 或者,如果它们是简单的十六进制数,则直接转换。

It would be really helpful if you can tell the data type you receive from C++ and the required format in python. 如果您可以告诉您从C ++接收到的数据类型以及python中所需的格式,那将非常有帮助。

Python has several options to process binary data; Python有几种处理二进制数据的选项。 in this case, you start out by reading from a socket, producing an immutable bytes buffer ( bytes in Python 3, str in Python 2). 在这种情况下,您将从读取套接字开始,生成一个不可变的字节缓冲区(Python 3中为bytes ,Python 2中为str )。 This can be parsed as 16-bit words using either struct.unpack or array.array : 可以使用struct.unpackarray.array将此解析为16位字:

tuple_of_ints = struct.unpack('=12000h', data)
array_of_s16s = array.array('h', data)

From there, you still have only a one-dimensional structure, where odd and even items are your I and Q values. 从那里开始,您仍然只有一维结构,其中奇数和偶数项是您的I和Q值。 If using numpy , you could use ndarray.fromstring or ndarray.frombuffer to create a similar array, then reshape it. 如果使用numpy ,则可以使用ndarray.fromstring或ndarray.frombuffer创建类似的数组,然后对其进行整形。

We could also convert items individually, which is a bit slower: 我们还可以单独转换项目,这有点慢:

list_of_complex_numbers = [complex(*struct.unpack('hh',data[i:i+4]))
    for i in range(0,len(data),4)]

numpy is also capable of reading from file, so with a file-like socket you might be able to use numpy.fromfile(socket, numpy.int16, 2*6000) . numpy还可以从文件读取,因此,通过类似文件的套接字,您可以使用numpy.fromfile(socket, numpy.int16, 2*6000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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