Go Down

Topic: "Overflow" for some long values (Read 657 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
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy