Converting int array to uint8

471 Views Asked by At

I have a function that returns a bool (8 times) in a loop, I want to construct an uint8_t, as you probably guessed I'm new to C and C++.

    unsigned int data[8];
    
    for(int i = 0; i < 8; i++) {
        // 1 or 0 if switch is on or off
        int value = (int)functionThatReturnsBool(i);
        data[i] = value;
    }
    
    // Needs B00000000 (with the correct switches on)
    functionThatNeeds(uint8_t ???);
2

There are 2 best solutions below

1
On

It's not completely clear what you're trying to do here, but if you're trying to pack 8 bools into one uint_8, something like this should trivially do it:

uint8_t packed = 0;
for(int i = 0; i < 8; ++i)
    packed = (packed << 1) | functionThatReturnsBool(i);

functionThatNeeds(packed);
0
On

As others have mentioned, it's not clear how your flags are supposed to be set in the resulting byte.

This example assumes that 'i' refers to the bit index.

uint8_t bits = 0x00;

for ( int i = 0; i < 8; i++ ) {
    if ( functionThatReturnsBool( i ) ) {
        bits |= 1 << i ;
    }       
}

functionThatNeedsBits( bits ) ;