Go Down

Topic: Weird integer casting result (Read 861 times) previous topic - next topic



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

Code: [Select]
void setup() {

void loop() {
  int pos = 7;
  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?


Coding Badly

Yup.  The code you posted is optimized by the compiler.  [font=Courier New]pow(2, pos-1)[/font] is calculated at compile time and the constant [font=Courier New]64[/font] 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 [font=Courier New]pow(2, pos-1)[/font] with [font=Courier New]1 << (pos-1)[/font].


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

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)


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

Go Up