Answer the question
In order to leave comments, you need to log in
Qt - How to convert int to QByteArray?
In general, it is necessary in Qt to convert an int number into a QByteArray byte array:
for now, I do this:
i
nt valueRange; //задаем 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;
Answer the question
In order to leave comments, you need to log in
You left out two important facts - that char is a signed type and that not all machines store a four-byte number in memory in the order of bits. (Pointed and blunt architectures).
If numbers need to be sent over a network, they must be converted to network byte order. This is what the hton...() family of methods does. The reverse transformation is done by the ntoh...() methods.
In QByteArray you can push it like this:
int i=42;
QByteArray s=QByteArray::fromRawData(reinterpret_cast<const char*>(i),sizeof(i));
Yes, not all the rules
>>> ((-1&0xff) << 24) + ((-1&0xff) << 16) + ((-2&0xff) << 8) + (-35 &0xff) & 0xffffffff
4294967005
>>> (-291) & 0xffffffff
4294967005
#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();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question