'convert an int to QByteArray in Qt

I'm trying to convert an int to QByteArray. I'm using this method QByteArray::number(m_vman); is it correct?

I'm trying to use the number() for getting an int to QByteArray.

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;


Solution 1:[1]

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.

Solution 2:[2]

you can simply do like this.

int myInt = 123;
QByteArray q_b;
q_b.setNum(myInt);

Solution 3:[3]

Related to the actual question title, the following static function should definitely work:

QByteArray::number

Solution 4:[4]

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;

Solution 5:[5]

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 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):

intValue:  42
bytes:     "2a:00:00:00:00:00:00:00"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kuba hasn't forgotten Monica
Solution 2 Kamlesh
Solution 3 Anonymous
Solution 4 IAmInPLS
Solution 5 Mike F.