首先:QByteArray 中没有这样的功能。但是,有很多方法可以解决它,只要您知道字节数组的长度。然而,有一件小事让这件事变得更加复杂:Endianess。
以下示例假定所有字节数组都有最大长度。该函数是通用的,因此您可以根据需要动态决定:
template <typename TInt>
void addNumber(QByteArray &data, TInt number) {
static_assert(std::is_integral<TInt>::value, "TInt must be an integral type");
constexpr auto maxSize = sizeof(TInt);
const auto dSize = data.size();
// make shure no data that is longer then the allowed integer size is passed
Q_ASSERT_X(dSize <= maxSize, Q_FUNC_INFO, "bytearrays longer than sizeof(TInt) byte are not allowed!");
// prepend '\0' bytes to the array to fill it up to an N byte length
if(dSize < maxSize)
data = QByteArray{maxSize - dSize, '\0'} + data;
// convert to a number, add and convert back
auto dataNum = qFromBigEndian<TInt>(data.constData());
dataNum += number;
qToBigEndian(dataNum, data.data());
// resize the data back to the original size, dropping the previously prepended bytes
if(dSize < maxSize)
data = data.mid(maxSize - dSize);
}
要使用该方法,只需找出您的字节数组可以有多长,然后使用相应类型的方法。例如,如果您的数据限制为最多 4 个字节(如评论中所述),您可以将其用作:
QByteArray ba = "\x8a\x0d\x8a";
addNumber<quint32>(ba, 1u);
// ba is now "\x8a\x0d\x8b"
重要提示:小心使用模板参数。明确指定它以确保您不会意外传递不同类型的文字。例如,将其简单地称为 addNumber(ba, 1) 会将 TInt 推导出为 int - 而不是一个未指定的 int。
编辑:
如果您将 bytearrays 字节序定义为与当前平台相同,则不需要进行此类转换。代码将更改为:
// convert to a number, add and convert back
*(reinterpret_cast<TInt*>(data.data())) += number;
这实际上取决于这些数据的来源以及您如何使用它。