-----Original Message----- From: Tracy Smith To: PICLIST@MITVMA.MIT.EDU Date: Tuesday, November 09, 1999 11:11 AM Subject: Re: Doing percentage or ratio >--- Nikolai Golovchenko wrote: > >> 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 > > Are you sure???: > >> clrf RegH >> rlf RegH, f >> ;*************************************** Yes, I am. With last two commands I copy 9th bit of result to RegH. If you know that result is 8 bit maximum you can skip these. So your version is okay too. > > >And the fast way: > > movf RegH,w > addwf RegL,f > skpnc > incf RegH,f > btfsc RegL,7 > incf RegH,f > >.lo > >===== > >__________________________________________________ >Do You Yahoo!? >Bid and sell for free at http://auctions.yahoo.com > > _ Nikolai Golovchenko, Electrical Engineering Student National Mining University of Ukraine www.nmuu.dp.ua Dnepropetrovsk, Ukraine E-mail: golovchenko@mail.ru