>-----Original Message----- >From: piclist-bounces@mit.edu [mailto:piclist-bounces@mit.edu] >Sent: 24 February 2005 21:34 >To: piclist@mit.edu >Subject: [PIC]: Fast Integer Division by a constant > > >Hi, > >I'm wondering if anyone has any clever algorithms for >performing 16 bit >integer division by a constant using the multiply instruction >in the 18F >instruction set. I've looked over the many standard division >routines, and >thought perhaps there may be ones that employ the hardware multiply to >really speed things up. > >Specifically, I need to scale a number (0 - 65535) to 0 - 2730 >(hence a >divide by 24.) Maybe I'm missing a real obvious approach, but I'd >appreciate any suggestions anyone might have. > >Thanks! > >- Mike Yes there is an easy way. To divide by 24, you multiply by 1/24. Obviously this isn't possible directly using integer math, but if you scale the multiplier by a nice binary factor, and then apply the same scaling to the result then things work nicely. e.g. in your case (x * (1/24) * 2^16)/2^16 (x * 2730)/2^16 So you simply multiply your number by 2730, giving a 32 bit result, and then use the top 16bits to get your scaled result. Regards Mike ======================================================================= This e-mail is intended for the person it is addressed to only. The information contained in it may be confidential and/or protected by law. If you are not the intended recipient of this message, you must not make any use of this information, or copy or show it to any person. Please contact us immediately to tell us that you have received this e-mail, and return the original to us. Any use, forwarding, printing or copying of this message is strictly prohibited. No part of this message can be considered a request for goods or services. ======================================================================= -- http://www.piclist.com PIC/SX FAQ & list archive View/change your membership options at http://mailman.mit.edu/mailman/listinfo/piclist