cmp instruction and negative numbers

772 Views Asked by At

Here is a code to sort the given array in assembly language

.model small
.stack 100h

.data           ;roll number 2435
data1 db 66h, 2, 045h, 4, 040h, 3, -025h, 5, -010h, 011h
swap db 0
.code
mov ax, @data
mov ds, ax
start:
mov swap, 0
mov bx, 0
loop1:
mov al, [bx+data1]
mov cl, [bx+data1+1]
cmp al, [bx+data1+1]      ;here is the problem when compare 66h with -025h
jbe noswap

mov dl, [bx+data1+1]
mov [bx+data1+1],al
mov [bx+data1], dl
mov swap, 1
noswap:
add bx,1
cmp bx,9
jne loop1

cmp swap,1
je start
mov ah, 04ch
int 21h

it compares all elements of array to sort in ascending order, but when it compares 66h with -025h, it implies that 66h is smaller and -025h is bigger and does not swap, mov to no swap lable

i have debugged it and found that at backend -025h is being stored as DB. How can I properly sort the array with negative number

1

There are 1 best solutions below

0
On

Use the signed condition code in the conditional branch: e.g. jle instead of the unsigned condition code jbe. See https://sandpile.org/x86/cc.htm . If you ask the processor to do unsigned condition then it will see -025h as 0xDB, which is 219, so larger than 66h/102.

The processor doesn't read data declarations, so it doesn't see the minus sign.  Since it never sees declarations, it doesn't matter to the processor if you put db -25h or db 219 or db 0xdb — these will all populate the data with the same bit pattern value.

In C, for example, we give types to the variables and then the compiler (using language rules) generates machine code that accesses the variable consistently, i.e. as the size it was declared, and also as to whether signed or unsigned.

In assembly language we don't have variable declarations with expressive type information.  So, we must do the job that compilers do: use the proper size and signed'ness in the machine code for every access to variables.