Hello everyone,

I write code in assembler, which subtracts two numbers. I need advice on how to modify the code subtracted from a positive number to a negative number.

For example:

826-(-621) = 1447

Thanks for you advice

; 826 = 0x33A,   961 = 3c1
; 576 = 0x240,   -621 = 0x
; 978 = 0x3D2,   -684 = 0x


    LIST P=18F87J11
    #include <P18F87J11.INC>
    CONFIG  FOSC = HS
    CONFIG  WDTEN = OFF
    CONFIG  XINST = OFF
    udata_acs 0x000

    addH        res     1   
    cary        res     1       
    a           res     1   
    b           res     1   
    c           res     1   
    d           res     1   
    addL        res     1   
    prodH       res     1   
    prodL       res     1   
    SOUCV       res     2   

    ORG 0x0000

    goto        Main            ; jdi na Main

Main:
    ;0x33A - 0x240
    movlw       0x03    ; nastav WREG na 0 hexa = 0000 0000
    movwf       a   ; WREG => addL => addL = 0
    movlw       0x3a    ; nastav WREG na 0 hexa = 0000 0000
    movwf       b
    movlw       0x02    ; nastav WREG na 0 hexa = 0000 0000
    movwf       c
    movlw       0x40    ; nastav WREG na 0 hexa = 0000 0000
    movwf       d
    movf        d   ; WREG <= 0xB8
    movwf       addH    ; WREG => addH => 0xB8
    movwf       prodL   
    clrf        SOUCV   

    clrf        cary    
    subwf       b
    movlw       0x03
    subwf       a
    movff b, SOUCV
    movff a, SOUCV+1

If I recall, virtually all computing devices perform subtraction by addition of the 2's complement of the subtrahend from the minuend. It's easier to see how this works in binary. For your example, writing the values 821 (0x33a) and -621 (0xfd93) in binary, you have:

0000 0011 0011 1010 - 1111 1101 1001 0011

Take the 2's complement of the subtrahend and 1111 1101 1001 0011 becomes:

0000 0010 0110 1101

These are then added:

0000 0011 0011 1010 + 0000 0010 0110 1101 = 0000 0101 1010 0111

The result (0x5A7) is the expected 1447 in decimal notation. The carry flag will be set on overflow (i.e., when the result is too large for the number of bits in the operands). In this case the result is the amount of overflow and can be used for extended precision arithmetic. Underflow is similar but requires examination of both the sign and carry bits.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.