首页 > 解决方案 > 如何防止 Matlab udp/fread 将原始字节数据转换为双精度

问题描述

我正在尝试从 UDP 读取编码的原始数据并将其传递给我的自定义 MEX 文件进行解码。现在,当我使用fread从我的 UDP 端口读取数据时得到的结果是双倍的。此外,udp/fread的文档告诉我们

默认情况下,数值以双精度数组的形式返回

但是,它没有说明的是如何防止这种转换以及如何获取原始字节值。我没有使用浮动值,并且必须在我的 MEX 文件中转换回来,这会导致不必要的开销。

编辑:根据要求,这是一个小例子。

u = udp();
u.LocalPort = 3333;
fopen( u );
data = fread( u, 10, 'uint8' );
fclose( u );

假设您通过这个 Python 小脚本发送:

import time
import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 3333
MESSAGE = "Hello, World!"

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
    sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
    time.sleep(.100)

正如 udp/fread 的文档所说,这将输入视为uint8并返回双精度值。然而,与fread 文档读取文件相比,UDP 版本似乎没有理解*=>语法来指定输出类型。

顺便说一句:我正在使用 R2017b,也许这也会有所作为。

标签: matlabudp

解决方案


您可以将'precision'输入用于freaddocs):

Form of the precision Input   Description

source                        Input values are of the class specified by source.
                              Output matrix A is class double.
                              Example: 'int16'

source=>output                Input values are of the class specified by source.
                              The class of the output matrix, A, is specified by output.
                              Example: 'int8=>char'

*source                       The input values and the output matrix, A, are of
                              the class specified by source. For bitn or ubitn precisions, 
                              the output has the smallest class that can contain the input.
                              Example: '*ubit18'
                              This is equivalent to 'ubit18=>uint32'

所以你应该可以使用

A = fread( fid, 2, '*int16' ); % Use correct size instead of 2 depending on your type

推荐阅读