# Subtraction in Assembly (positive and negative number)

Page 1 of 1

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

### #1 MaxDJs

Reputation: 0
• Posts: 2
• 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

```    ; 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

cary		res		1
a			res		1
b			res		1
c			res		1
d			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
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		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

Reputation: 103
• Posts: 679
• 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