QDataStream和QByteArray

一个写操作可以参考:

QDataStream &operator >>(QDataStream &in, SerializedMessage &message)
{
   qint32 type;
  qint32 dataLength;
  QByteArray dataArray;
  in >> type >> dataLength;
  dataArray.resize(dataLength);  // <-- You need to add this line.
  int bytesRead = in.readRawData(dataArray.data(), dataLength);
  // Rest of function goes here.
}

 

void SomeClass::slotReadClient() { // slot connected to readyRead signal of QTcpSocket
    QTcpSocket *tcpSocket = (QTcpSocket*)sender();
    while(true) {
        if (tcpSocket->bytesAvailable() < 4) {
           break;
        }
        char buffer[4]
        quint32 peekedSize;
        tcpSocket->peek(buffer, 4);
        peekedSize = qFromBigEndian<quint32>(buffer); // default endian in QDataStream
        if (peekedSize==0xffffffffu) // null string
           peekedSize = 0;
        peekedSize += 4;
        if (tcpSocket->bytesAvailable() < peekedSize) {
           break;
        }
        // here all required for QString  data are available
        QString str;
        QDataStream(tcpSocket) >> str;
        emit stringHasBeenRead(str);
     }
}

 

QString占两字节,转成一个字节可以用toUtf8()。
Per the Qt serialization documentation page, a QString is serialized as:

- If the string is null: 0xFFFFFFFF (quint32)
- Otherwise:  The string length in bytes (quint32) followed by the data in UTF-16.
If you don't like that format, instead of serializing the QString directly, you could do something like

stream << str.toUtf8();
How I can remove it, including last null byte?
You could add the string in your preferred format (no NUL terminator but with a single length header-byte) like this:

const char * hello = "hello";
char slen = strlen(hello);
stream.writeRawData(&slen, 1);
stream.writeRawData(hello, slen);
QVariantMap myMap, inMap;
QByteArray mapData;

myMap.insert("Hello", 25);
myMap.insert("World", 20);

QDataStream outStream(&mapData, QIODevice::WriteOnly);
outStream << myMap;
qDebug() << myMap;
QDataStream inStream(&mapData, QIODevice::ReadOnly);
inStream >> inMap;
qDebug() << inMap;

 

转载于:https://www.cnblogs.com/ph829/p/6145680.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值