Pow() function gives incorrect answer while using variable as exponent.

factor = pow(2, travel);

When travel is 0, or 1, it sets factor to the correct number.
When travel is 2, 3, 4 or 5 (That’s as high as I have travel go), however, it sets factor to the incorrect number.
If travel = 2, factor is set to 3
If travel = 3, factor is set to 7
If travel = 4, factor is set to 15
If travel = 5, factor is set to 31

My complete code is this:

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int Byte;
int Speed = 1000;
int LengthIn = 2;
int Length;
int travel;
int factor;
int Time;
void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  Serial.begin(9600);
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, 0);
  digitalWrite(latchPin, HIGH);
  if(LengthIn = 3) {
    Length = 3.5;
  }
  if(LengthIn = 2) {
    Length = 3;
  }
  Serial.print("Length = ");
  Serial.println(Length);
  delay(2000);
}
void loop() {
  while(Time < 1) {
    travel = 0;
    while(travel <= 5) {
      Serial.print("Travel = ");
      Serial.println(travel);
      factor = pow(2, travel);
      Serial.print("Factor = ");
      Serial.println(factor);
      Byte = Length * factor;
      Serial.print("Byte = ");
      Serial.println(Byte);
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, LSBFIRST, Byte);
      digitalWrite(latchPin, HIGH);
      travel = travel + 1;
      delay(Speed);
    }
    //while(travel >= 0) {
      //Serial.println(Byte);
      //Byte = Length * pow(2, travel);
      //digitalWrite(latchPin, LOW);
      //shiftOut(dataPin, clockPin, LSBFIRST, Byte);
      //digitalWrite(latchPin, HIGH);
      //travel = travel - 1;
      //delay(Speed); 
  //}
   Time = Time + 1;
  }
}

And I know that it sets factor to the incorrect number because the serial monitor gives me this:

Length = 3
Travel = 0
Factor = 1
Byte = 3
Travel = 1
Factor = 2
Byte = 6
Travel = 2
Factor = 3
Byte = 9
Travel = 3
Factor = 7
Byte = 21
Travel = 4
Factor = 15
Byte = 45
Travel = 5
Factor = 31
Byte = 93

The incorrect factor then screws up my “Byte” variable, which screws up everything. How can I fix this?

pow returns a float. Floats don’t store numbers exactly, so sometimes 16 ends up being stored as 15.9999. So when you try to put that into an int it gets truncated and ends up as 15. You could add 0.5 to the answer before you convert to an int

BUT there is a better way. You don’t need pow for powers of 2. We’re working in binary here. Just use a bitshift. It’s a whole lot faster and gets the right answer.

1 << n == 2^n

1 << 0 == 1
1 << 1 == 2
1 << 2 == 4
1 << 3 == 8
1 << 4 == 16

etc. etc.