Hello.

I set an arbitrary array

QBitArray msg (8); msg.setBit(7, listBit.at(1).toInt()); msg.setBit(6, listBit.at(2).toInt()); msg.setBit(5, listBit.at(3).toInt()); msg.setBit(4, listBit.at(4).toInt()); msg.setBit(3, listBit.at(5).toInt()); msg.setBit(2, listBit.at(6).toInt()); msg.setBit(1, listBit.at(7).toInt()); msg.setBit(0, listBit.at(8).toInt()); 

at the same time the array can be 16 bits and so on. I need to get the value out of it and output it.

There is a function on the Internet

 QByteArray bitsToBytes(const QBitArray &bits) { QByteArray bytes; bytes.resize(bits.size()/8); // Convert from QBitArray to QByteArray for(int b=0; b<bits.count(); ++b) bytes[b/8] = (bytes.at(b/8) | ((bits[b]?1:0)<<(b%8))); return bytes; } 

However, the result is incorrect. Please tell me how to implement

    1 answer 1

    It seems that rounding down in bytes.at(b/8) is not done. Probably better this way:

     QByteArray bitsToBytes(const QBitArray &bits) { QByteArray bytes; bytes.resize(bits.size()/8); for(int b = 0; b < bits.count(); ++b) bytes[b/8] = (bytes.at(std::floor(b/8)) | ((bits[b]?1:0)<<(b%8))); return bytes; } 

    And you can still do it easier, but with a small overhead projector:

     QBitArray msg(8); msg.setBit(7, 1); msg.setBit(6, 1); msg.setBit(5, 1); msg.setBit(4, 1); msg.setBit(3, 1); msg.setBit(2, 1); msg.setBit(1, 1); msg.setBit(0, 1); QByteArray data; QDataStream stream(&data, QIODevice::WriteOnly); stream << msg; data.remove(0, sizeof(quint32)); qDebug() << data; 

    The last but one line will remove the size of the bitmap that is written to the stream during serialization.

    • Writes error C: \ Qt \ Qt5.3.2 \ Tools \ QtCreator \ bin \ ftdi \ main.cpp: 31: error: 'floor' is not a member of 'std' bytes [b / 8] = (bytes.at ( std :: floor (b / 8)) | ((bits [b]? 1: 0) << (b% 8))); ^ - tw333k
    • Include the header file "<cmath>" via include . - alexis031182