4

I think I’m a kind of at a loss here. I trying such a simple thing, I can’t believe that there is nothing build-in Qt (using Qt 5.6.2). I try to convert the data inside a QByteArray from big endian to little endian. Always starts with the same test QByteArray like this.

QByteArray value;
value.append(0x01);
value.append(0x02);
value.append(0x03);
qDebug() << "Original value is: " << value.toHex(); // “010203” like expected

What I need is the little endian, which means the output should be “030201”. Is there any build in thing so far in the Qt Framework? I don’t find one. What I tried so far

// Try with build in QtEndian stuff
QByteArray test = qToLittleEndian(value);
qDebug() << "Test value is: " << test.toHex(); // 010203

// Try via QDataStream
QByteArray data;
QDataStream out(&data, QIODevice::ReadWrite);
out.setByteOrder(QDataStream::LittleEndian);
out << value;
qDebug() << "Changed value is: " << data.toHex(); // "03000000010203"

Any good idea? Or do I really need to shift hands by hand? Found nothing helpfull on SO or on google or maybe ask the wrong question...

Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47
sandkasten
  • 603
  • 1
  • 8
  • 21
  • 2
    A single byte is the same in big- or little-endian. Do these bytes represent some other data type? – bnaecker May 09 '18 at 15:42
  • Hmm.. maybe I'm on the false track? Do I need more a reverse function? These bytes comes direct from a measurment unit which sends the data as bytes in little endian encoding. The data is a compound of different values put togehter. So first I need to correct the data bevore working on. – sandkasten May 09 '18 at 15:46
  • What is the exact data type that the measurement unit sends you? `char`, `uint16_t`, `double`, etc. – bnaecker May 09 '18 at 15:48
  • As I meantioned bevore, it's a compounded value which need to be interpreted by decoding the QByteArray. But this is done later. First, I need to change the order. Don't hang on the data type. As written in the question, I just want another QByteArray in the 'right' order. – sandkasten May 09 '18 at 15:50
  • 3
    The concept of endianness only applies to multi-byte data types. So the "right" order depends on what the data type is. But if you just want to reverse the array, I'd use `std::reverse` from the C++ algorithms library. – bnaecker May 09 '18 at 15:54
  • Jep, you brought me on the right track,the std::reverse is exactly what I needed! Please put your comments and the solution in an answer I will accept it later, I'm off now, thanks! – sandkasten May 09 '18 at 15:56

1 Answers1

10

It sounds like you want to reverse the array, rather than manipulate the endianness of any of the multi-byte types inside the array. The standard library has a solution for this:

QByteArray arr;
std::reverse(arr.begin(), arr.end());
// arr is now in reversed order
bnaecker
  • 6,152
  • 1
  • 20
  • 33