Showing posts with label Assembly Language. Show all posts
Showing posts with label Assembly Language. Show all posts

Thursday, April 26, 2007

Concat Two User Provided Strings

.model small
.stack 100h
.data

; Its recommended to display a message to user before every input and output

; Message for first input
msg1 db "Enter the first string: $"

; Message for second input
msg2 db 0ah, 0dh, "Enter the second string: $"

; Message for third input
msg3 db 0ah, 0dh, "New string is: $"

; For each buffered input, we have to reserve space such that
tsize1 db 10        ; First byte contains a value that indicates the number of characters to be received at maximum
asize1 db ?         ; Second byte is reserved for interrupt's use
array1 db 10 dup(?) ; The third byte and on for saving the input. The minimum amount of space required
                    ; here is equal to the value of first byte


; For second input
tsize2 db 10
asize2 db ?
array2 db 10 dup(?)

; Here both values would be concatenated. So, it must be sum of the sizes of both inputs long
array3 db 20 dup('$')

.code

main:

; Set the value of ds
mov ax, @data
mov ds, ax

; Display first message
mov ah, 09h
mov dx, offset msg1
int 21h

; Get first input
mov ah, 0ah
mov dx, offset tsize1
int 21h

; Display second message
mov ah, 09h
mov dx, offset msg2
int 21h

; Get second input
mov ah, 0ah
mov dx, offset tsize2
int 21h

; Copy first string

; Loop uses cx register
mov cx, 0 ; So clean it up first
mov cl, asize1 ; Put actual size of first input in cl

; cx
; 0 7
; ch cl

; The value of cx is same as value of cl now

mov si, offset array1    ; Offset of first byte of first input is moved in si
mov di, offset array3    ; Offset of first byte of new string is moved in di ; Here the loop starts

start1:

mov al, [si]    ; Copy the value at the address of si in al (one byte)
mov [di], al    ; Copy this value at the address of di from al

inc si          ; Move to next byte of source
inc di          ; Move to next byte of target

loop start1

; loop subtracts 1 from cx and checks if its zero. Zero means break the loop
; So, the loop appears to run cx times which has number of characters in first input

; First string copied, start the second

mov cx, 0
mov cl, asize2

mov si, offset array2  ; Start copying from first byte of second string
                       ; But the target remains the same

start2:

mov al, [si]
mov [di], al
inc si
inc di

loop start2

; Copy complete

; Display message
mov ah, 09h
mov dx, offset msg3
int 21h

; Display the string
mov dx, offset array3
int 21h

; Exit
mov ah, 4ch
int 21h

end main