Arduino Forum

Using Arduino => Programming Questions => Topic started by: _Matt_ on May 01, 2012, 05:37 pm

Title: Mistakes with shift operation
Post by: _Matt_ on May 01, 2012, 05:37 pm
Hello everybody, can you please help me to find the mistake here? I can't understand what's the problem (probably some over overflow).
Here's my code:

Code: [Select]
uint32_t value = 0;

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

void loop()
{
  for (int i = 0; i < 32; i++)
  {
    value = 1 << i;
   
    Serial.print("value["); Serial.print(i); Serial.print("] = ");
    Serial.print(value);
    Serial.print(" - binary = ");
    Serial.println(value, BIN);
  }
 
  while(1);
}


This is what I obtain (as you can see the values after the 14th are messed up)
(http://i.imgur.com/RrtcL.png)

I've also tried declaring value as an unsigned long (same results) and as an unsigned int (value[15] = 32768, value[16+] = 0). How to fix? Thank you for your help!
Title: Re: Mistakes with shift operation
Post by: Marek080 on May 01, 2012, 06:21 pm
Code: [Select]
value = uint32_t(1) << i;
Try this one in your loop. Looks like the compiler uses int for the 1 and int is only 16 bit. If you shift 16 times the 1 gets lost...
Title: Re: Mistakes with shift operation
Post by: _Matt_ on May 01, 2012, 06:23 pm
Now it works, thank you!