Go Down

Topic: Mistakes with shift operation (Read 991 times) previous topic - next topic

_Matt_

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)


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!

Marek080

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

_Matt_


Go Up