1 Replies - 2832 Views - Last Post: 10 December 2012 - 01:50 AM

#1 MaxDJs  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-December 12

Subtraction in Assembly (positive and negative number)

Posted 05 December 2012 - 11:03 AM

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



Is This A Good Question/Topic? 0
  • +

Replies To: Subtraction in Assembly (positive and negative number)

#2 turboscrew  Icon User is offline

  • D.I.C Addict

Reputation: 100
  • View blog
  • Posts: 610
  • Joined: 03-April 12

Re: Subtraction in Assembly (positive and negative number)

Posted 10 December 2012 - 01:50 AM

Basically, negative number is 2's complement of the positive number.
(I'ts actually "overflow-mathematics").
=> First change all "1"s to "0"s and vice versa. Then add 1 to the result.


Subtracting a number is adding the negative of that number.

If you use "subwf" you need to handle the carry and overflow status flags.
I'm not sure how your device handles the carry in subtraction (I don't have the instruction set, and I don't really know the PICs), but usually you clear the carry-flag, do the low-byte subtraction, then do the high byte subtraction(s) (in order). The subtraction instruction then subtracts the numbers and one more (borrow) if the carry was set. The carry is then set to reflect the borrow-status of this new subtraction.

In some other devices it works differently.

The overflow might happen, is the result "changes" the sign. That's why you need to check the overflow-flag.

This post has been edited by turboscrew: 10 December 2012 - 01:52 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1