Qt — How to convert an int to a QByteArray?

In General, it is necessary in the Qt int to convert to a byte array QByteArray:
while doing so:
i
nt valueRange; //set valueRange 

char a = ( valueRange >> 24 )& 0xFF;
char b = ( valueRange >> 16 )& 0xFF;
char c = ( valueRange >> 8 )& 0xFF;
char d = valueRange & 0xFF;

byte->append(a);
byte->append(b);
byte->append(c);
byte->append(d);

qDebug() << " val:" << valueRange << " = " << (int)a <<"*"<<(int)b<<"*"<<(int)c<<"*"<<(int)d;


But when you get output such as this:
val: -291 = -1 * -1 * -2 * -35
val: -141 = -1 * -1 * -1 * 115
val: -200 = -1 * -1 * -1 * 56
val: 105 = 0 * 0 * 0 * 105


As it is not the right kind of work.
Perhaps there is some standard way? it's Qt.
September 19th 19 at 00:27
3 answers
September 19th 19 at 00:29
You left out two important facts - that char - character type and that not all of the machines the four-byte number is stored in memory in accordance with the order discharges. (Pointed and obtuse architecture).

If numbers need to be transmitted over the network, they must be converted to network byte order. This makes the family of methods hton...(). Reverse transformation methods do ntoh...().

In QByteArray you can push like this:
int i=42;
QByteArray s=QByteArray::fromRawData(reinterpret_cast<const char*>(i),sizeof(i));</const>
September 19th 19 at 00:31
Yes, not all the rules

>>> ((-1&0xff) << 24) + ((-1&0xff) << 16) + ((-2&0xff) << 8) + (-35 &0xff) & 0xffffffff 
4294967005
>>> (-291) & 0xffffffff
4294967005


You only need to understand that the right shift of a negative number implementation defined behaviour, i.e. the results will be intelligible, but may vary depending on platform and compiler.

(stackoverflow.com/questions/4009885/arithmetic-bit...)
September 19th 19 at 00:33
#include
#include
#include
#include

int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);

int i = 1045632159;
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);

stream << i;

int newValue = qFromBigEndian( (const uchar*)byteArray.constData() );

qDebug() << "newValue:" << newValue;

return app.exec();
}

Find more questions by tags Qt