'How to convert a two-dimensional byte array into a single byte (Arduino)?

I have this array:

bool data[] = {{1,1,1,1},{0,0,0,0}};

And I need to convert it into bool data type like this:

byte data = 11110000;

Any ideas?



Solution 1:[1]

You can try something like this:

#define COLUMNS 2
#define ROWS 4
#define SIZE (COLUMNS * ROWS)


bool data[COLUMNS][ROWS] = {{1, 1, 1, 1}, {0, 0, 0, 0}};

byte result = 0;
int shift = SIZE;

for (int i = 0; i < COLUMNS; i++) {
    for (int j = 0; j < ROWS; j++) {
        result |= data[i][j] << --shift;
    }
}

Solution 2:[2]

Another solution with single loop, for single or multidimensional arrays.

bool data[2][4] = { { 1, 1, 1, 1 }, { 0, 0, 0, 0 } };

bool *pointer = reinterpret_cast<bool*>(data);
unsigned int value = 0;
for (unsigned int index = 0; index < sizeof(data); ++index) {
    value <<= 1;
    value |= *pointer++;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Patricklaf