Pages: [1]   Go Down
Author Topic: "Overflow" for some long values  (Read 626 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 2
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


unsigned long mult;


void setup() {
Serial.begin(9600);
}
void loop() {
 
  mult = 33 * 1000;
  Serial.println (mult);

}

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

0
Offline Offline
Faraday Member
**
Karma: 16
Posts: 2855
ruggedcircuits.com
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: