Weird integer casting result

Hi,

I'm stumped by the following issue. Consider the following code:

void setup() {
  Serial.begin(9600);
}

void loop() {
  int pos = 7;
  Serial.println(pos);
  Serial.println((int) pow(2, pos-1));
}

This outputs 7 followed by 64 (2 to the power of 6), as expected.

When I have the exact same code (I copied and pasted) inside a full and more complex sketch, the output I get is 7 followed by 63. The variable "pos" is declared as an integer in that sketch as well.

Any idea what could be causing this?

Thanks.

Yup. The code you posted is optimized by the compiler. pow(2, pos-1) is calculated at compile time and the constant 64 is put in the expression's place.

The code you did not post has an expression that cannot be calculated at compile time.

The solution is simple. Replace pow(2, pos-1) with 1 << (pos-1).

well known and discussed here every month ..

pow does use floating point math and is subject to rounding. Casting it to an int round it down to the nearest int (aka floor) If you want to have proper rounding you can do

Serial.println((int) (pow(2, pos-1) +0.5));

or create a lookup table (array) with precalculated values.

For the powers of 2 you can also do shifting (fastest)

Serial.println(1UL << (pos-1)); // shifts the bit on position 0 (pos -1) positions to the left effectively multiplying by 2 in every next position

Thank you very much for both replies. Perfectly clear now.