What is the best way to cast Quint16 to QBitarray(16) ?

  • Hi all,

    What is the best way to cast Quint16 to QBitarray(16) ?


  • Hi!
    I don't think there's a 'nice' way. So maybe something like this:

    QBitArray quint16ToQBitArray(quint16 v)
        QBitArray ba(16);
        for (int i=0; i<16; i++)
            ba.setBit(i, v>>i & 1);
        return ba;
    quint16 qBitArrayToQuint16(const QBitArray &ba)
        quint16 v = 0;
        for (int i=0; i<16; i++)
            v |= ba.at(i)<<i;
        return v;

  • Qt Champions 2017

    If you feel lazy and don't want to run for loops, as I usually do, you could also try:

    quint16 value; //< Your value
    QByteArray data = QByteArray::fromRawData(reinterpret_cast<char *>(&value), sizeof(quint16));
    QDataStream stream(&data, QIODevice::ReadOnly);
    QBitArray bitArray(sizeof(quint16));
    stream >> bitArray;

    Although it doesn't seem to be shorter than @Wieland's suggestion.

    Kind regards.

  • Hi,

    @kshegunov I tried the same thing also your code but I could not manage it to work.. I have already have a Qdatastream, I get quint16 values from it... I tried your solution at first sight...

    @Wieland The code you send works fine thank you very much..

    Have Nice day guys.. Thanks for your help.. It's very valuable..

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.