Jose Miguel Ledón
Jose Miguel Ledón

Reputation: 309

wrong value at pow function in for loop

I'm trying to make an IP calculator on Arduino, but in this part Im getting a wrong result, i'm expecting a 128, but it returns 127, I think the problem is in the pow function(2,i) because if I hardcode the pow with a (2,7) I get the 128. this is the code

result=0;
binNumber="10110100"; //I this bin number in another function
firstchar= binNumber.substring(0, 1); //extract the first char
c0="0000000"; 
fullNumber= firstchar + c0;
for(int i=0;i<=7;i++){
  x = String (fullNumber[7-i]);
  xint= x.toInt();
  result= result + xint * pow(2,i);
}
lcd.print(result);

Upvotes: 0

Views: 97

Answers (1)

abligh
abligh

Reputation: 25169

Don't use pow(2,i). Use 1<<i. By using bit shifts, you will avoid possible floating point errors.

Upvotes: 1

Related Questions