20000*4 != 80000 !!!!!

Hey guys,
I don't really have a problem any more as I spent my last 4 hours trying to solve this problem. Though I still don't understand! I want to know the reason why this happened with me cuz I'm kinda going crazy.
I have this following code in a function which simply reads a sensor and calculates a result and I'm trying to show it in my main program using the Serial. read():
unsigned long ticks;
long e_read;
ticks = 20000 * 4;
e_read = something.read();
return map(e_read % ticks, 0, ticks, 0, 360);
The result I was getting was wrong the whole time as I know what is coming out of something.read(). I suspected everything.. I tried replacing the % operator, replacing the map with simple math code and using "if" instead of the "condition ? : " formula (doesn't show in the code I posted).
I finally tried something I though would be stupid but I was so desperate. I simply replaced the (20000 * 4) with 80000. It worked!!
Now I'm getting the results I want. I'm writing this because I was going so crazy that I even used a calculator to calculate (20000 * 4) before I posted this! And I want others to benefit from that if they have this problem.
Dying to know the answer!
please excuse my long text, thx!

20000 and 4 are both treated by the compiler as 16 bit signed integers (by default) so the multiply overflows.
Use notation like 20000L or 20000UL if you want to force the calculation to be done as long signed or unsigned integers, respectively.

Its all to do with the size of things - long answers will follow for now change ticks = 20000 * 4; to ticks = 20000UL * 4;


Oh! Oh, thx for the answer...
I thought one doesn't have to do that between long and int. Good to know.. But does that apply only for the Arduino compiler or is it also like that for the C or C++ compilers?

All, the Arduino uses the standard gcc compiler. It also applies in most other languages, you must watch your type at all times.


PS 2/3 is 1


Could you save me trying to figure out how 2/3 = 1 and post the code?
With ints I usually get 2/3 = 0.

Could you save me trying to figure out how 2/3 = 1 and post the code?
With ints I usually get 2/3 = 0.

Of course you do! 2/3 IS 0

Put another way, 3 goes into 2, 0 times, with a remainder of 2.

ints don't do floating point.

Now read reply #4 and consider the thread topic.