R
R
Roman Khudoberdin2020-02-07 11:42:14
Qt
Roman Khudoberdin, 2020-02-07 11:42:14

How to put and remove bit fields in QByteArray without pain?

There is a QByteArray, how to put into it, and then extract the bit fields?
No bitwise shifts.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ponomarev, 2020-02-07
@pon79

It would be good to see in the context of what situation you need it, since the way the extraction depends on it.
In the simplest case:

#include <QCoreApplication>
#include <QDebug>

struct Device {
    bool mainPower: 1;
    bool reservePower: 1;
    bool alarm: 1;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Device dev1{ true, false, true };

    QByteArray arr;
    arr.append( (char*) &dev1 );

    // куда-то передали arr

    char c{ arr.at(0) };
    Device *pDev1 = reinterpret_cast<Device *>( &c );

    qDebug() << pDev1->mainPower;
    qDebug() << pDev1->reservePower;
    qDebug() << pDev1->alarm;

    return a.exec();
}

J
Jacob E, 2020-02-07
@Zifix

How about using https://doc.qt.io/archives/qt-4.8/qbitarray.html?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question