2

I've CRC value into uint that is:

95DF

My target is return from uint two byte in QByteArray.

I get this:

`CRC uint 95DF

//in simple i should return this

QByteArray[0] = 95;
QByteArray[1] = DF;

I've tryed convert uint to QString but this one change return value. Ho to keep the result and return QByteArray ?

Thanks

Community
  • 1
  • 1
Mr. Developer
  • 3,295
  • 7
  • 43
  • 110

2 Answers2

1
unsigned int value = 0x95df;
char bytes[2] = {};
bytes[0] = (value >> 8) & 0xff;
bytes[1] = value & 0xff;
QByteArray qba(bytes, 2);

Alternatively:

unsigned int value = 0x95df;
value = qToBigEndian(value); // for x86 and little endian, this puts the bytes in expected order. no-op on big-endian
QByteArray qba((char*)&value, 2);
selbie
  • 100,020
  • 15
  • 103
  • 173
  • 1
    with htons work correctly, instead with qToBigEndian don't work in qt. I've use htons. Thanks – Mr. Developer Jul 10 '17 at 09:01
  • @Mr.Developer - I only made about a dozen typos writing that answer out. Please double check my latest revision answer before pasting into your code. – selbie Jul 10 '17 at 09:02
0

You can also use QDataStream to achieve this:

QByteArray qba;
QDataStream qbaStream(&seq,QIODevice::WriteOnly);
qbaStream << static_cast<quint16>(value);
IlBeldus
  • 1,040
  • 6
  • 14