Pages: [1]   Go Down
Author Topic: Weird integer casting result  (Read 452 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Jr. Member
**
Karma: 0
Posts: 99
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,

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

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.
Logged

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 208
Posts: 12932
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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).
Logged

Global Moderator
Netherlands
Offline Offline
Shannon Member
*****
Karma: 217
Posts: 13739
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Logged

Rob Tillaart

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

Offline Offline
Jr. Member
**
Karma: 0
Posts: 99
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Logged

Pages: [1]   Go Up
Jump to: