On Fri, Feb 5, 2010 at 1:44 AM, Johannes Bauer <jb....@gmx.de> wrote: > Dear list, > > I'm trying to do rounded (opposed to truncated) integer division with > avr-gcc with using only preprocessor magic. This proves to be difficult: The > current code I'm using is > > #define __IDIV(x, y) (long)(((long)x + ((long)y / 2L)) / (long)y) > #define IDIV(x, y) (__IDIV((x), (y)))
> Is there another way to do it? /* * #define UART_BAUD_SELECT (F_CPU/(UART_BAUD_RATE*16L)-1) * * When doing integer divide it is usually better to round to the nearest * integer, rather than to the lowest (which the above expression does). * * Add 0.5 (i.e. half the value of the denominator) * to the numerator before the division. This can be achieved in the * following way: * * #define UART_BAUD_SELECT ((F_CPU + UART_BAUD_RATE * 8L) /\ * (UART_BAUD_RATE * 16L) - 1) * - Neil Johnson AVR-GCC List */ #define UART_BAUD_CALCULATE(UART_BAUD_RATE) ((F_CPU + UART_BAUD_RATE * 8L) / (UART_BAUD_RATE * 16L) - 1) -- http://www.wearablesmartsensors.com/ http://www.softwaresafety.net/ http://www.designer-iii.com/ http://www.unusualresearch.com/ _______________________________________________ AVR-GCC-list mailing list AVR-GCC-list@nongnu.org http://lists.nongnu.org/mailman/listinfo/avr-gcc-list