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);
    return result;

but it doesnt this work?

Thanks and kind regards Nic

  • "Does not work" is a poor problem description. Explain what it actually does and what you expected it to do. Provide a minimal but complete test sketch, that shows the problem – chrisl Nov 20 '19 at 20:51
  • You seem to want to convert an array of bools into the respective integer value, so e.g. { false, true, true, false} into 0b0110 = 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 signed int. – Maximilian Gerhardt Nov 20 '19 at 22:16
  • The pow function returns a float. Floats are inherently inaccurate. The index to the array has to be an int. When you do powers of 2 with pow you don’t actually get 4. You get 3.9999999 something. So when that gets truncated it turns into 3 and not the 4 that you want. Use bit shifting for integer powers of 2 and you won’t have this problem. – Delta_G Nov 21 '19 at 15:45
  • Thank you Guys a lot! It worked like a charm but I could not have made it without you! – Nic Nov 22 '19 at 12:43

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;

The ternary operation (b_array[id] ? (1 << run) : 0) means:

  • If b_array[id] is true, then
    • Or result with 1 left-shifted run times and store in result
  • otherwise
    • Or result with 0 and store the result (no-operation).
| improve this answer | |
  • 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 example result = (result<<1) | b_array[id]; more (it can be result = result*2 + b_array[id] too) – KIIV Nov 22 '19 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 Nov 22 '19 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.