Years ago a friend of mine asked me for help to code a program in assembly language to determine if a text string is a palindrome or not. The palindrome is a word or phrase which reads the same backward and forward. I came with the following solution that receives a parameter through command line and determines if it is a palindrome or not.
The program is interesting as it also shows how to receive and handle parameters passed through command line in assembly language, and reveals a buil-in way to determine the parameter size, which in this program helps reduce code.
; Create Date: 2007
; Last modified: June 2016, added comments, translated to english.
; This program receives a word (without spaces) via command line and will place it in extra segment (ES)
; It determines if the provided word is a palindrome or not
; A palindrome is a word or phrase that is read the same forward and backward.
; Execution instructions:
; >[program name][space][word that will be evaluated]
PRINTST MACRO STRING
LEA DX, STRING
MOV AH, 9
INT 21H
ENDM
.model small
.data
TEMP1 DW 0
PALMESSAGE DB " THE PROVIDED STRING IS A PALINDROME $"
NOTPALMESSAGE DB " THE PROVIDED STRING IS NOT A PALINDROME $"
.CODE
inicio:
mov ax,@data
mov ds,ax
MOV SI, 82H
;SI is the left pointer, the first char will be located at offset 82h, on ES register.
MOV DI, 80H
;DI is the right pointer, It will start at offset 80h + (Low register of ES:[80h])
; MOV AX, ES:[80h] ; Low portion of ES:[80h] stores the argument length + 1, for example for tacocat it will be ; 8.
MOV AH, 0
; The high portion of ES:[80h] has unneeded data, therefore it is zeroed.
MOV TEMP1, AX
; AX stores the length, and it is passed to TEMP1.
ADD DI, TEMP1
; D1 + TEMP1 = offset of last character on the string.
COMPARE:
MOV DL, ES:[SI]
;Return the ascii code of the character pointed by the left pointer on the string.
MOV DH, ES:[DI]
;Return the ascii code of the character pointed by the right pointer on the string.
CMP DL, DH
;If the characters are the same, then Z=0.
JNE NOTPAL
;If Z!=0, chars were different, so it will go to NOTPAL, print that it is not a palindrome and exit.
MOV TEMP1, SI
CMP TEMP1, DI
;If the pointers point to the same character (Z=0), it means the word was fully compared and that it is a palindrome,
JAE PAL
;So it jumpts to Pal, to print the message.
INC SI
;If the pointers are not on the same offest, it will move the left pointer a position to the right
DEC DI
;and the right pointer a position to the left
JMP COMPARE
;and will keep comparing the rest of the characters.
PAL:
PRINTST PALMESSAGE
Prints the text: THE PROVIDED STRING IS A PALINDROME.
JMP FIN
NOTPAL:
PRINTST NOTPALMESSAGE
Prints the text: THE PROVIDED STRING IS NOT A PALINDROME.
FIN:
;End instructions.
mov ah,4ch
;Exit to operating system.
Int 21h
END INICIO