Shop OBEX P1 Docs P2 Docs Learn Events
Divide by 10 — Parallax Forums

Divide by 10

GAFGAF Posts: 25
edited 2007-09-09 22:53 in General Discussion
In the September issue if Nuts & Volts there was an article on floating point math on a 8-bit·chip.· Using what the author outlined I came up with a simple routine to divide a byte by 10 and determine the remainder.· This routine only involves simple shift and add instructions. In the following code X is the byte that will be divided by 10, tmp1 and tmp2 are just temporary variables. The "Result" contains the answer to the division.

tmp1 = X>>2
tmp1 = tmp1 + X
tmp2 = tmp1>>1
tmp2 = tmp2 + X
Result= tmp2>>4

tmp1 = Result<<2
tmp1 = tmp1 + Result
tmp2 = tmp1 << 1
Remainder = X - tmp2

I have used this routine in a couple of my SX programs and it seems to work fine.

Comments

  • BeanBean Posts: 8,129
    edited 2007-09-09 00:43
    Unless tmp1 and tmp2 are WORD variables, they will overflow.

    Here is what I suggest for a fast divide by 10 with remainder:


    ' Byte divide by 10 with remainder DEVICE SX28, OSC4MHZ, TURBO, STACKX, OPTIONX
    FREQ 4_000_000
     
    x         VAR BYTE
    result    VAR BYTE
    remainder VAR BYTE
     
    PROGRAM Start NOSTARTUP
    
     
    Start:
      x = 0
     
      ASM 'Divide by 10
        MOV remainder,x
        CLR result
        MOV W,#160
        SUB remainder,W
        RL result
        SB result.0
        ADD remainder,W
        MOV W,#80
        SUB remainder,W
        RL result
        SB result.0
        ADD remainder,W
        MOV W,#40
        SUB remainder,W
        RL result
        SB result.0
        ADD remainder,W
        MOV W,#20
        SUB remainder,W
        RL result
        SB result.0
        ADD remainder,W
        MOV W,#10
        SUB remainder,W
        RL result
        SB result.0
        ADD remainder,W
     ENDASM
     'result = x / 10
     'remainder = x // 10
    END
    
    


    This is basicly and "unrolled" version of the normal division code.

    Bean

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    The first rule to being successful is "Learn from your mistakes",
    The second rule is "Be willing to make mistakes"
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    www.hittconsulting.com


    Post Edited (Bean (Hitt Consulting)) : 9/9/2007 1:05:31 PM GMT
  • GAFGAF Posts: 25
    edited 2007-09-09 22:53
    Thanks Bean, I will give it a try. I see your point on my routine.
Sign In or Register to comment.