Question

This function doesnt work correctly for some inputs, So What is the mistake ?

All Projects Codes here : link

ps: I am using input that "bits.size()%8" equal to zero

QByteArray bitsToBytes(QBitArray bits) {
  QByteArray bytes;
  bytes.resize(bits.count()/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;
}
Was it helpful?

Solution

Topro algorithm should be correct as a whole. But my concert is with the test bits[b]?1:0.

By default, operator[] ( int i ) return "the bit at index position i as a modifiable reference" while operator[] ( int i ) const return a boolean. If the first definition is chozen, you will test if a reference is true.

Try Topro algorithm with bits.testBit(b).

OTHER TIPS

i think it's maybe the bits shall be left shifted (7 - (b % 8)) bits

I tried this and got the expected result.

QBitArray bits;
QByteArray bytes;

bits.resize(12);
bits.fill(true);

bits.setBit(2,false);

bytes.resize((bits.count() - 1) / 8 + 1);

for(int b=0; b<bits.count(); ++b)
    bytes[b/8] = ( bytes.at(b/8) | ((bits[b]?1:0)<<(7-(b%8))));

for (int b=0;b<bytes.size();b++)
    printf("%d\n",(quint8)bytes.at(b));

Consider the case, where (bits.count() % 8) != 0 , e.g. 9 Then bytes.resize(bits.count()/8); returns the wrong result.

As Topro suggested in a comment, you could use bytes.resize((bits.count() - 1) / 8 + 1)).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top