快速将quint16/unsigned short附加到QByteArray [英] Append quint16/unsigned short to QByteArray quickly

查看:809
本文介绍了快速将quint16/unsigned short附加到QByteArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我正在使用QByteArrays在程序运行时向其添加数据.在大多数情况下,使用QByteArray::append()可以将简单的quint8附加好.但是,当附加quint16时,仅附加1个字节而不是2个字节.

In my project I'm working with QByteArrays appending data to them as the program goes. Most of the time, a simple quint8 gets appended just fine using QByteArray::append(). But when a quint16 gets appended, only 1 byte gets appended instead of 2.

QByteArray ba = QByteArray::fromHex("010203");
quint number(300);//300 in hex is 012c

ba.append(number);//What should be appended instead of just number?

//the current incorrect result is
ba.toHex() == "0102032c"

//the desired result is
ba.toHex() == "010203012c"

我已经尝试过了,但是它只是将值插入为一个字符串(4个字节):

I've already tried this, but it just inserts the value as a string (4 bytes):

ba.append(QByteArray::number(number, 16));

我应该在QByteArray后面附加什么,以便数字"的两个字节都被附加而不是仅一个字节?另外,由于该程序需要具有较高的性能时间,因此最好选择最快的方法.因此绝对不需要转换为QStrings.

What should I append to the QByteArray so both bytes of "number" get appended instead of just one byte? Also, the fastest method possible is preferred since this program needs to have great performance times. So absolutely no converting to QStrings.

感谢您的时间.

推荐答案

QByteArray本身仅支持附加字节.要附加固定大小整数类型的big-endian表示形式,您可以使用适当的移位来构建自己的operator<<(或您喜欢的)重载:

On its own, QByteArray only supports appending bytes; to append a big-endian representation of fixed-size integer types you can build your own operator<< (or what you prefer) overloads using the appropriate bit shifts:

QByteArray &operator<<(QByteArray &l, quint8 r)
{
    l.append(r);
    return l;
}

QByteArray &operator<<(QByteArray &l, quint16 r)
{
    return l<<quint8(r>>8)<<quint8(r);
}

QByteArray &operator<<(QByteArray &l, quint32 r)
{
    return l<<quint16(r>>16)<<quint16(r);
}

这使您可以编写如下代码:

This allows you to write code like:

QByteArray b;
b<<quint16(300);     // appends 0x01 0x2c
b<<quint8(4);        // appends 0x04
b<<quint16(4);       // appends 0x00 0x04
b<<quint32(123456);  // appends 0x00 0x01 0xe2 0x40
b<<quint8(1)<<quin16(2)<<quint32(3); // appends 0x01 0x00 0x02 0x00 0x00 0x00 0x03

您应该避免写作

QByteArray b;
b<<1;

由于理论上输出取决于当前平台整数的大小(尽管Qt int支持的所有平台上的AFAIK是32位).

because in theory the output depends on the size of the current platform integer (although AFAIK on all platforms supported by Qt int is 32 bit).

这篇关于快速将quint16/unsigned short附加到QByteArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆