Search code examples
cbit-fields

Pushing boolean values of an array to uint8 bitfield


Let's suppose I have:

myArray[7] = {TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE}

uint8 mybitfield;

What is the most efficient way to "push" those values to an uint8 bitfield with 0=FALSE, 1=TRUE

So that mybitfield is represented as:

[1,0,0,1,1,0,0,0] 

(The Least Significant Bit is not considered and will be always 0).

Thanks!


Solution

  • As already noted, you have to iterate over the bits individually, for example:

    int myArray[7] = {TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE};
    
    uint8_t bitfield = 0;
    for (int i = 0; i < 7; ++i) {
        bitfield |= myArray[i] ? 1 : 0;
        bitfield <<= 1;
    }
    

    This results in 0b10011000, i.e., the array has the most significant bit first and an implicit zero for the least significant bit.