P
P
Philip Bondarev2017-09-24 12:09:21
Qt
Philip Bondarev, 2017-09-24 12:09:21

How to get its binary representation from a QByteArray element?

Good afternoon.
I have a QByteArray of an image received over the serial port. Each element of QByteArray is 1 pixel (8 bits), color from 0 to 255. I need to form 8 pictures from this base image. The generation algorithm is as follows:
Take the least significant (zero, right) bit of the first pixel of the source image, if it is 0 , then the first byte (pixel) of the first generated image must be black ( '00000000' , '0x00' , 0 ), if the least significant bit of the first pixel of the source image is 1 , then the first byte(pixel) of the first generated image must be white( '11111111' ,'0xFF' , 255 ). We also act with the first bit of the first pixel of the original image, but we form the first pixel of the second image, and so on for the first pixels of all the remaining ones. The operation is repeated for all pixels of the original image, thereby forming 8 two-color images.
Using Python 2.7 , I implemented the algorithm like this:

def run(self):
        self.start_gen.emit(len(self.source_img))
        pb_val = 0
        for img in self.nine:
            self.nine[img] = bytearray(b'')
        for byte_ in self.source_img:
            pb_val += 1
            self.generating.emit(pb_val)
            bit_str = by2bi(byte_)
            for i in range(8):
                if bit_str[i] == '0':
                    self.nine['img_' + str(i)] += self.b0
                else:
                    self.nine['img_' + str(i)] += self.b255
        self.stop_gen.emit()

But when rewriting the whole thing in C ++ , stupid problems arose due to lack of experience.
For example, how do I cast a QByteArray element to '00001111' so that I can loop through the bits and compare them to zero or one? How do I form the bytes '0x00' and '0xFF' to write each picture to the QByteArray ?
It seems to me that we need to solve this whole thing with bitwise operations, but how?
And yet, in Python , I just take and create a dictionary with arrays to write values ​​​​to them, how can I do this in C ++ ? I thought that it should be formed
QVector<QByteArray> generated_images;
However, the compiler complains that it is impossible to form a vector filled with QByteArray 's.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
devalone, 2017-09-24
@devalone

Something like this for example

for(size_t y = 0; y < height; ++y) {
  for(size_t x = 0; x < width; ++x) {
    for(unsigned char i = 0; i < 8; ++i) {
      bool bit = (bytes[width * y + x] >> i) &1;
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question