piclist 2001\04\03\084532a >
Thread: Any clever implementations of rounding out there ?
www.piclist.com/techref/microchip/devices.htm?key=pic
picon face BY : Bob Ammerman email (remove spam text)



[warning: untested code]

I don't know if this is clever, but it is simple.

Assuming positive values:

int round(int value, int granularity)
{
   value += granularity >> 1;
   value /= granularity;
   return value * granularity;
}

If time isn't an issue and you want to avoid multiply/divide:

int round(int value, int granularity)
{
   int result = 0;
   value += granularity >> 1;
   while (value > granularity)
   {
       result += granularity;
       value -= granularity;
   }
   return result;
}

Or, similarly:

int round(int value, int granularity)
{
   int result = 0;
   value += granularity >> 1;

   for (;;)
   {
       value -= granularity;
       if (value <= 0)
           break;
       result += granularity;
   }
}

Or even:

int round(int value, int granularity)
{
   value += granularity >> 1;
   result = 0;
   while (result <= value)
       result += granularity;
   return result;
}

Conversion to assembly is an exercise for the user (or compiler) :-)

Bob Ammerman
RAm Systems
(contract development of high performance, high function, low-level
software)

--
http://www.piclist.com hint: The list server can filter out subtopics
(like ads or off topics) for you. See http://www.piclist.com/#topics


<00c401c0bc3a$6d4f1c00$f2e8c540@CDS> 7bit

See also: www.piclist.com/techref/microchip/devices.htm?key=pic
Reply You must be a member of the piclist mailing list (not only a www.piclist.com member) to post to the piclist. This form requires JavaScript and a browser/email client that can handle form mailto: posts.
Subject (change) Any clever implementations of rounding out there ?

month overview.

new search...