Go Down

Topic: "Overflow" for some long values (Read 635 times) previous topic - next topic

peterperez


unsigned long mult;


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

 mult = 33 * 1000;
 Serial.println (mult);

}

33 * 1000 gives 4294934760 instead 33000 ... why?!?!?!?

RuggedCircuits

Try "33UL * 1000U".

33 and 1000 are both (16-bit) integers and their product is a 16-bit integer, but the range of these is [-32768,32767] so the result is already an overflow: 33000-65536=-32536 so 33*1000 = -32536.

Then, the number -32536 gets stored as an unsigned long: 2^32 - 32536 = 4294934760, which is the number you observed.

Go Up