Search code examples
c++qthexqbytearray

How to append an enum represented by a series of hex values to QByteArray?


I have some enums which are represented by series of hex values in the following manner:

enum someEnum
{
    NameA = 0x2121,
    NameB = 0x2223,
    NameC = 0x2020
};

I want to append one of these enums to QByteArray in the following way:

QByteArray anArray;
anArray.append(NameA);

But this approach produces the warning

implicit conversion from 'int' to 'char' changes value from 8481 to 33.

In fact, even if I do the following:

anArray.append(static_cast<char>(NameA));

it only appends 0x21 (in decimal 33).

I also tried doing the following:

const char * t = reinterpret_cast<char*>(NameA);
anArray.append(t, sizeof(t));

but that leads to a segmentation fault.

I could of course do the following without any loss of value or crash or any other problem:

anArray.append(0x21);
anArray.append(0x21);

But I don't want that, I want to directly append the enum. Could you please suggest a correct way to do it?

Thanks a lot.


Solution

  • Probably you can use QDataStream:

    QByteArray byteArray;
    QDataStream dataStream(&byteArray, QIODevice::WriteOnly);
    
    dataStream << NameA;
    

    Sorry, but I do not have qt available right now and i cannot tested this