trouble with pow() function

If I use pow(2,3) result is 8 but if I use that in folllowing code result is 7 instead of 8. pow(2,0) = 1, pow(2,1) = 2 but starting from pow(2,2), using variable 'positie' instead of a value, the result is one less then it should be :confused: :confused:

Any ideas?

String getal = "11111101";
  int basis = 2;
  int cijfer;
  int cijferwaarde;
  int uitkomst = 0;
  int positie = 0;
  int lengte = getal.length();
  int x;
  int y = 3;
  
  // berekening per cijfer
  for (positie = 0; positie < lengte; positie++) {
     cijfer = getal.substring(lengte-positie-1,lengte-positie).toInt();
     cijferwaarde = cijfer * pow(basis,positie);
     uitkomst += cijferwaarde;
     Serial.print(positie);
     Serial.print(" ");
     Serial.print(cijfer);
     Serial.print(" ");
     Serial.println(cijferwaarde);
  }

Result:
0 1 1
1 0 0
2 1 3
3 1 7
4 1 15
5 1 31
6 1 63
7 1 127

This is the reference for pow(): pow() - Arduino Reference
Basically, pow() returns a double value. However, in computer world, floating number can have a little bit "offset". For example: 2^3 ~ 7.9999999999..., when you cast that number to an integer, it becomes 7.

Okay apparently positie value 3 is somehow just under 3. How to solve? Use round()?

ruud00000:
Okay apparently positie value 3 is somehow just under 3. How to solve? Use round()?

yes

For integer powers of two, 2N = 1<<N. Much faster than pow() and, the answer is exact.