Reputation: 664
I'm new in arduino programming (c/c+). And would like to convert a array with bool's to an byte like. The booleans repreprents a buttons here.
bool array[] = {0,1,1,0}; // needs to convert to 0b0110
// bool array[] = {1,0,0,0}; // needs to convert to 0b1000
// bool array[] = {true,true,false,true}; // needs to convert to 0b1101
void setup(){
byte b = convert(array); // 0b0110
}
byte convert(bool array[]){
byte b = 0b + 0 + 1 + 1 + 0; // <- wrong stuff here :(
return b;
}
Upvotes: 1
Views: 683
Reputation: 7409
I can't rewrite all your code right now, but I can lay out a basic algorithm. I think it'll help you.
You need something, either in a loop or hardcoded (if you really only have four bits). For brevity, I'm going to call your array a
and I'll just hardcode the calculation so it's super-clear.
If you think of the entries of your array in bits, it's like this:
eights fours twos ones
{ 0 , 1 , 1 , 0 }
You get these values by using the left-shift operator <<
which doubles the value for each shift.
So with the leftmost member of your array as the most significant bit, you do it like this:
shift 3 shift 2 shift 1 no shift
uint8_t b = (a[0] << 3) + (a[1] << 2) + (a[2] << 1) + a[3];
so -> no eights one four one two no ones
6 = 0 + 4 + 1 + 0
Do you see the pattern? Each less significant bit is shifted by one LESS to the left, halving its total value. The sum of these values is your byte value (uint8_t
).
There are other notations which have the same effect, but this one is the easiest to understand.
Now to the booleans. You could use the ternary operator and test each element, something like this:
uint8_t b = (
(a[0] ? 1 << 3 : 0) +
(a[1] ? 1 << 2 : 0) +
(a[2] ? 1 << 1 : 0) +
(a[3] ? 1 : 0 )
);
Once you see this pattern, you can do all sorts of cool bitwise constructions with it.
Upvotes: 1