[英]convert an int to QByteArray in Qt
I'm trying to convert an int to QByteArray
.我正在尝试将 int 转换为QByteArray
。 I'm using this method QByteArray::number(m_vman);
我正在使用这种方法QByteArray::number(m_vman);
is it correct?这是正确的吗?
I'm trying to use the number()
for getting an int to QByteArray
.我正在尝试使用number()
获取QByteArray
的 int。
I'm trying the following code but the bytearray is zero我正在尝试以下代码,但字节数组为零
QByteArray vmanByteArray, vheaterByteArray;
QDataStream streamVMan(&vmanByteArray, QIODevice::WriteOnly);
QDataStream streamVHeater(&vheaterByteArray, QIODevice::WriteOnly);
streamVMan << m_vman;
streamVHeater << m_vheater;
QByteArray arr = m_htman ? vmanByteArray : vheaterByteArray;
you can simply do like this.你可以简单地这样做。
int myInt = 123;
QByteArray q_b;
q_b.setNum(myInt);
Related to the actual question title, the following static function should definitely work:与实际问题标题相关,以下静态函数肯定可以工作:
I flagged as a duplicate because you could have searched better (seriously, there are dozen of questions like that).我标记为重复是因为你可以搜索得更好(说真的,有很多这样的问题)。 Anyway, this is the easiest solution:无论如何,这是最简单的解决方案:
int myInt;
QByteArray bA;
QDataStream stream(&bA, QIODevice::WriteOnly);
stream << myInt;
The array is not zero, your code works fine:该数组不为零,您的代码工作正常:
#include <QtCore>
QByteArray test(bool m_htman) {
int m_vman = 1;
int m_vheater = 2;
QByteArray vmanByteArray, vheaterByteArray;
QDataStream streamVMan(&vmanByteArray, QIODevice::WriteOnly);
QDataStream streamVHeater(&vheaterByteArray, QIODevice::WriteOnly);
streamVMan << m_vman;
streamVHeater << m_vheater;
QByteArray arr=m_htman ? vmanByteArray: vheaterByteArray;
return arr;
}
int main() {
auto one = QByteArray() + '\0' + '\0' + '\0' + '\1';
auto two = QByteArray() + '\0' + '\0' + '\0' + '\2';
Q_ASSERT(test(true) == one);
Q_ASSERT(test(false) == two);
}
It may be "zero" if the values stored in it are zeroes, but that'd be correct.如果存储在其中的值为零,则它可能是“零”,但这是正确的。
This thread is quite old as I just stumbled across the issue (or a similar one), here is my suggestion:这个线程很老,因为我只是偶然发现了这个问题(或类似的问题),这是我的建议:
To store the value of the integer variable (what the value is is not exactly defined here, I mean the memory representation in bytes) in a QByteArray I suggest:要在 QByteArray 中存储 integer 变量的值(此处未准确定义值,我的意思是 memory 以字节表示),我建议:
QByteArray arr = QByteArray::fromRawData(reinterpret_cast<const char *>(&m_vman), sizeof(m_vman));
Test case:测试用例:
#include <QtCore>
int main() {
qint64 intValue = 42;
QByteArray bytes = QByteArray::fromRawData(reinterpret_cast<const char *>(&intValue), sizeof(intValue));
qDebug() << "intValue: " << intValue;
qDebug() << "bytes: " << bytes.toHex(':');
}
Output (bytes is little endian representation): Output(字节为小端表示法):
intValue: 42
bytes: "2a:00:00:00:00:00:00:00"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.