使用 QTcpSocket 发送字节
Sending Bytes using QTcpSocket
我有一个嵌入式设备,我试图通过无线连接通过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 将允许我写入字符数据或 QByteArray,但是当我尝试以这两种格式中的任何一种保存此数据时,它会失败。 我成功保存数据的唯一方法是在无符号字符数组中。
我的意思的例子:
char message[12] = {
0x55, 0x55, 0x55, 0x55,
0x01, 0x00, 0x00, 0x00,
0xAA, 0xAA, 0xAA, 0xAA};
但是,此消息块给了我一个错误
C4309: 'initializing' : truncation of constant value.
打印此数据时,结果为:
U U U U
r
R 更像是正方形的边缘,而不是实际的字母
通过将数组从 char 更改为无符号 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);
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 在UNIX系统中使用DIR查找文件的字节大小
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- std::当在256字节边界上写入整数时,流的奇怪行为
- 当比特(而不是字节)的顺序至关重要时的持久性
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 如何在文件中查找字节序列
- luaL_dofile在已知良好的字节码上失败,可以使用未编译的版本
- QTcpSocket在不阻塞GUI的情况下重新连接到服务器
- 字节到位运算符重载C++
- 在java中读取c++字节的位字段
- 使用 std::vector::reverse_iterator 将 int 序列化为字节向量?
- 字节真的是最小可寻址单元吗
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- 如何使用QTcpSocket读取超过8192字节?
- 使用 QTcpSocket 发送字节
- 为什么我的代码无法读取 QTcpSocket 上可用的字节数?想法?
- 当主线程在无限循环中运行时,用QTcpSocket::write写入的字节没有被服务器接收