# simple arithmetic problem

I am trying to take analog potentiometer read 0-1023 and converting it to analog output of 0-255

int potval
int outputvalue

when I do outputvalue = 255/1023 * potval

i get outputvalue sometimes random negative values..

But then I found an example on the web that solves the problem by adding a decimal point to 255 and 1023 ie

outputvalue = 255./1023. * potval

the above statement works great, I am wondering why?? what is the reason for this??

`when I do outputvalue = 255/1023 * potval`Without the decimal point this calculation will be treated as if the results of all calculations within it are ints.

Incidentally, take a look at the map() function to do what you want.

joefly:
I am trying to take analog potentiometer read 0-1023 and converting it to analog output of 0-255

int potval
int outputvalue

when I do outputvalue = 255/1023 * potval

i get outputvalue sometimes random negative values..

If you do integer calculation the term "255/1023" should be 0 and stay 0, no matter what factor you then multiply it with.

Is there any "interrupt handling routine" involved?

Or do you another calculation than you told? Perhaps outputvalue = 255 * potval /1023 or similar?

joefly:
But then I found an example on the web that solves the problem by adding a decimal point to 255 and 1023 ie

outputvalue = 255./1023. * potval

the above statement works great, I am wondering why?? what is the reason for this??

Forcing your constants to be floating point numbers creates a floating point calculation and the integer part of the final result is then assigned to an integer. This should work, but is slow.

In normal cases, when you want to reduce a 10-bit integer to an 8-bit integer, you just shift 2 bits to the right:

``````outputvalue = potval>>2;
``````

Or if you don't know anything about shifting bits, you'd do an integer division by 4:

``````outputvalue = potval/4;
``````

jurs:
Or if you don't know anything about shifting bits, you'd do an integer division by 4:

``````outputvalue = potval/4;
``````

Actually, the /4 is a better choice, because it better conceptually models the scaling that he's doing. The compiler will probably optimize it to a right shift anyway.