I found a "bug" for me today. I working with a 12m long treadmill for positioning. One revolution is 150000 pulses and fits in a LONG. I use a 16-bit value for positioning 65535, 65535 also fits in a LONG.

I also found that if I split my calculation in two parts it works…

long mapidimap(long x, long in_min, long in_max, long out_min, long out_max) {
unsigned long calc1 = (x - in_min) * (out_max - out_min);
unsigned long calc2 = calc1 / (in_max - in_min);
return calc2;
}

oqibidipo:
mapidimap(i, 0, 65535, 0 , 150000) simplifies to i * 150000 / 65535.
i * 150000 overflows long when i = 14317 and unsigned long when i = 28634.

Solution: use long long for intermediate results.

Better solution: use arithmetic.

150000 = 15 * 10000
65535 = 15 * 4369

Therefore, for i * 150000 / 65535, we can substitute i * 10000L / 4369, and it will not overflow unless i exceeds 214748.

But if I would speed up my code, isn´t it be better to not change the type inside the calculation and go for Whandall´s solution? "UNISGNED LONG" all he way...

But if I would speed up my code, isn´t it be better to not change the type inside the calculation and go for Whandall´s solution? "UNISGNED LONG" all he way...

All that does is change when the overflow will occur.

Better solution: use arithmetic.

That's fine in that specific case. It is not a general solution.

MacTommy:
When I run this code my "LONG mapedNumber" runs like an integer. It run to 32768 and jumps to -32768, but I would have this going up to 65535 instead.

So, you want unsigned integers rather than signed integers.