gpt4 book ai didi

c++ - 使用 QTcpSocket 发送字节

转载 作者:行者123 更新时间:2023-11-28 06:29:04 25 4
gpt4 key购买 nike

我有一个嵌入式设备,我正尝试通过无线连接通过 TCP 与其进行通信。以下是设备期望的数据结构:

char[] = { 0x55, 0x55, 0x55, 0x55 //header block
//start data here
0x01, 0x00, 0x00, 0x00 //example data
//end data block
0xAA, 0xAA, 0xAA, 0xAA //footer
};

我正在尝试使用 QTcpSocket 来写入此数据。 QTcpSocket 将允许我写入 char 数据或 QByteArray,但是当我尝试以这些格式中的任何一种保存此数据时,它会失败。我能够成功保存数据的唯一方法是在无符号字符数组中。

我的意思的例子:

char message[12] = {
0x55, 0x55, 0x55, 0x55,
0x01, 0x00, 0x00, 0x00,
0xAA, 0xAA, 0xAA, 0xAA};

但是,这个消息 block 给我一个错误

C4309: 'initializing' : truncation of constant value.

当打印这些数据时,结果如下:

U U U U
r

与实际字母相比,r 更像是正方形的边缘

通过将数组从 char 更改为 unsigned char 可以解决此特定问题

unsigned char message[12] = {
0x55, 0x55, 0x55, 0x55,
0x01, 0x00, 0x00, 0x00,
0xAA, 0xAA, 0xAA, 0xAA};

打印出来的数据是:

85 85 85 85
1 0 0 0
170 170 170 170

这与我正在通话的设备所期望的格式相匹配。但是,如果我以这种格式放置数据,QTcpSocket 不喜欢那样,并回复:

C2664: 'qint64 QIODevice::write(const QByteArray &)': cannot convert argument 1
from 'unsigned char[20]' to 'const char *'

有没有办法使用 QTcpSocket 发送我想要的数据,或者我是否需要弄清楚如何使用 Windows 套接字编写此消息?

最佳答案

您可以简单地转换为 char * :

qint64 ret = socket.write((char *)message, 12);

关于c++ - 使用 QTcpSocket 发送字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27969877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com