[Solved]Convert from qint32 to qbytearray
-
How to convert from qint32 to 4bytes QByteArray and how to convert back from QByteArray to qint32?
-
Is that what you are looking for: "setNum":http://qt-project.org/doc/qt-4.8/qbytearray.html#setNum
If not, maybe use a QDataStream and << num
and if also not I did not understand your question. -
If the QByteArray is only going to contain a qint32, you could use fromRawData. Alternately you can create a char* with the address of the integer and append from there. The latter technique works in reverse as well to get the qint32 back from the byte array.
-
[quote author="butterface" date="1349040456"]Is that what you are looking for: "setNum":http://qt-project.org/doc/qt-4.8/qbytearray.html#setNum
If not, maybe use a QDataStream and << num
and if also not I did not understand your question.[/quote]That would first convert the number to a "printable" ASCII string and then set the QByteArray these characters. If you want to create a QByteArray containing the "raw" bits of a qint32 value, you can do something like like:
@qint32 x = 42;
QByteArray foo = QByteArray::fromRawData(reinterpret_cast<char*>(&x), sizeof(qint32));@ The above won't copy the data though, it just wraps the pointer. To copy the data, you may use: @qint32 x = 42;
QByteArray foo(sizeof(qint32), '\0'); //Create QByteArray of required size
memcpy(foo.data(), &x, sizeof(qint32)); //Copy the data into the QByteArray@ Should also work: @qint32 x = 42;
QByteArray foo(reinterpret_cast<char*>(&x), sizeof(qint32));@ -
This code works:
@QByteArray array;
qint32 x = 11;
array.append((const char*)&x, sizeof(x));@How to convert it back to qint32?
-
You can use MuldeR's memcpy in reverse
@
// in
qint32 x = 42;
QByteArray foo(sizeof(qint32), '\0'); //Create QByteArray of required size
memcpy(foo.data(), &x, sizeof(qint32)); //Copy the data into the QByteArray
//out
qint32 y;
Q_ASSERT(foo.size() > sizeof(y));
memcpy(&y, foo.data(), sizeof(y));
@or even
@
//out
Q_ASSERT(foo.size() > sizeof(qint32));
qint32 y = (reinterpret_cast<qint32>(foo.data()));
@If in and out occur on different machines then you must consider the order that bytes are written in.
-
I'd just use a QDataStream:
@
//write
QByteArray target;
QDataStream s(&target);
qint32 value = someValue;
s << value;//read
qint32 value;
QByteArray source;
QDataStream s(&source);
s >> value;
@This way is much saver than using direct casts. It will work across small and big endian systems, for instance.
-
Thanks for any answer, this is the solution for me:
@
//write
QByteArray target;
QDataStream s(&target, QIODevice::ReadWrite);
qint32 value = someValue;
s << value;//read
qint32 value;
QByteArray source;
QDataStream s(&source, QIODevice::ReadWrite);
s >> value;
@ -
@andre ++1 for mentioning the "Endian" systems