=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Date: Mon, 08 Nov 1999 11:23:51 From: "Nikolai Golovchenko" To: "pic microcontroller discussion list" Subject: Re: Doing percentage or ratio -------------------------------------------------------------------------------- Hello! This message may be a little bit late :) The topic was about how to divide a 16 bit number by 255 and round the result. I only now clarified for myself the way to do this. Better later than never.. There was a suggestion to take higher byte and add one if MSB of lower byte is set. This method is not correct for every number. For example 383/255 (~=2) will give 1. 1/255 In binary form is 0.0000 0001 0000 0001 0000 0001.... This means that for 16 bit divident and rounded result two values should be added: b15b14b13b12b11b10b9b8.b7b6b5b4b3b2b1b0 and 0.b15b14b13b12b11b10b9b8. You can see that the division and rounding result is b15b14b13b12b11b10b9b8 + e, where e=0, 1, or 2 depending on sum of fractional parts. The correct way is: cblock RegH ;higher byte RegL ;lower byte endc ;*******Divide by 255**************** ;RegL, RegH - input ;RegL, RegH - output ;*************************************** movf RegH, w addwf RegL, f clrw btfsc _C movlw 1 btfsc RegL, 7 addlw 1 addwf RegH, w movwf RegL clrf RegH rlf RegH, f ;*************************************** _ Nikolai Golovchenko, Electrical Engineering Student National Mining University of Ukraine www.nmuu.dp.ua Dnepropetrovsk, Ukraine E-mail: golovchenko@mail.ru