M
M
mrZurg2015-03-01 23:21:31
Qt
mrZurg, 2015-03-01 23:21:31

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;

But when outputting, for example, I get 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

Somehow it does not seem to work correctly.
Perhaps there is some standard way? it's Qt.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Armenian Radio, 2015-03-02
@gbg

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

L
Lolshto, 2015-03-02
@Lol4t0

Yes, not all the rules

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

You just need to understand that shifting a negative number to the right is implementation defined behavior, i.e. the results will be intelligible, but may vary depending on the platform and compiler.
( stackoverflow.com/questions/4009885/arithmetic-bit... )

K
Khanik, 2017-07-13
@Khanik

#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 question

Ask a Question

731 491 924 answers to any question