Hey I wrote this function to convert an bool array to int: (Math Lob included):
bool b_array[5];
int convertToInt(start_index,stop_index){
int run=0;
int result=0;
for(int id=start_index;id<=stop_index;id++){
result+=b_array[id] * pow(2.0,run);
run++;
}
return result;
}
but it doesnt this work?
Thanks and kind regards Nic
chrisl
16.6k2 gold badges18 silver badges27 bronze badges
1 Answer 1
Assuming little-endian bools (least significant bool first), you should use simple bit-shifting, not floating point power calculations:
for(int id=start_index;id<=stop_index;id++){
result |= b_array[id] ? (1 << run) : 0;
run++;
}
The ternary operation (b_array[id] ? (1 << run) : 0
) means:
- If
b_array[id]
is true, then- Or
result
with 1 left-shiftedrun
times and store inresult
- Or
- otherwise
- Or
result
with 0 and store the result (no-operation).
- Or
answered Nov 20, 2019 at 23:12
-
You can simplify this in C++ because bool value promoted to an integer is 0 or 1. So
(b_array[id] << run)
can be used. In C there is no bool data type, so something like((b_array[id] !=0) << run)
should be used. And i like for exampleresult = (result<<1) | b_array[id];
more (it can beresult = result*2 + b_array[id]
too)KIIV– KIIV2019年11月22日 09:05:59 +00:00Commented Nov 22, 2019 at 9:05 -
Thank you for your Solution and your explaination, it worked on first try like a charm! Thank you a lot, I could not have solved that without your help!Nic– Nic2019年11月22日 12:44:26 +00:00Commented Nov 22, 2019 at 12:44
{ false, true, true, false}
into0b0110
= 6? Then you should use better casting, so(int)b_array[id]
and(int)pow(2.0,run)
. Though it's a weird way to do it, since bitshifting would be more appropriate (result += b_array[id] ? (1 << run) : 0
) . Also be aware of the numerical limits of your 16-bit signedint
.