]> git.sur5r.net Git - cc65/blob - libsrc/common/divt.s
Handle arguments outside char range correctly
[cc65] / libsrc / common / divt.s
1 ; divt.s
2 ;
3 ; 2002-10-22, Greg King
4 ;
5 ; This signed-division function returns both the quotient and the remainder,
6 ; in this structure:
7 ;
8 ; typedef struct {
9 ;     int rem, quot;
10 ; } div_t;
11 ;
12 ; div_t __fastcall__ div (int numer, int denom);
13 ;
14 ; Both sides of an assignment-expression must be cast to (long)
15 ; because cc65 functions can't return structures -- yet.  Example:
16 ;
17 ; #include <stdlib.h>
18 ; div_t answer;
19 ;
20 ; (long)answer = (long)div(-41, +3);
21 ; printf("The quotient is %d, and the remainder is %d.\n",
22 ;       answer.quot, answer.rem);
23
24         .export         _div
25
26         .import         tosdivax, negax
27         .importzp       sreg, ptr1, tmp1
28
29 _div:   jsr     tosdivax        ; Division-operator does most of the work
30         sta     sreg            ; Quotient is in sreg
31         stx     sreg+1
32         lda     ptr1            ; Unsigned remainder is in ptr1
33         ldx     ptr1+1
34
35 ; Adjust the sign of the remainder.
36 ; It must be the same as the sign of the dividend.
37 ;
38         bit     tmp1            ; Load high-byte of left argument
39         bpl     Pos             ; Jump if sign-of-result is positive
40         jmp     negax           ; Result is negative, adjust the sign
41
42 Pos:    rts
43