Skip to content

Instantly share code, notes, and snippets.

@Rhomboid
Created March 9, 2015 03:22
Show Gist options
  • Save Rhomboid/a62294a48accfb6b1202 to your computer and use it in GitHub Desktop.
Save Rhomboid/a62294a48accfb6b1202 to your computer and use it in GitHub Desktop.
MS-DOS string reverse program
.model small
; int 21h functions used:
DOS_PRINTSTR equ 09h ; output a $-terminated string in DS:DX
DOS_INPUT equ 0ah ; read buffered input into structure at DS:DX
DOS_EXIT equ 4ch ; terminate program with exit code in AL
.stack
.data
prompt_text db 'Enter a string: $'
output_text db 0ah, 0dh, 'Your string reversed: $'
input_buffer db 100, ; size of buffer
0, ; on output, will contain number of chars read, excluding CR
100 dup (0) ; the actual buffer
reversed_string db 100 dup (0)
.code
entry_point:
; establish the proper segment registers
mov ax, @data
mov ds, ax
mov es, ax
; print the prompt
mov ah, DOS_PRINTSTR
mov dx, offset prompt_text
int 21h
; read a string
mov ah, DOS_INPUT
mov dx, offset input_buffer
int 21h
; DI points to the first char of the destination
mov di, offset reversed_string
; CX contains the number of chars in the string
xor ch, ch
mov cl, byte ptr [input_buffer + 1]
; SI points to the last char of the source
mov si, offset input_buffer + 1
add si, cx
revloop:
; read a char from DS:SI and write to ES:DI, and increment SI and DI by 1
movsb
; undo the increment, and move to the previous char
sub si, 2
; decrement CX and branch if nonzero (repeast loop CX times)
loop revloop
; store a $ character at ES:DI, appending it to the output
mov al, '$'
stosb
; print the text and the reversed string
mov ah, DOS_PRINTSTR
mov dx, offset output_text
int 21h
mov dx, offset reversed_string
int 21h
; terminate program with exit code 0
xor al, al
mov ah, DOS_EXIT
int 21h
end entry_point
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment