Home > Software design >  stored string in stack gets printed reversed in boot sector assembely code
stored string in stack gets printed reversed in boot sector assembely code

Time:08-24

i wrote a simple boot sector assembly program that pushes each character that is entered in keyboard to the stack but when i try to retrieve each character from top of the stack and print them as a whole the result is in reverse. i know im reading it from the top so it gets reversed please tell me how to do this correctly

mov ax,0x800
mov ss,ax

mov ax,0x7c0
mov ds,ax
mov cx,0

mov bp,0
mov sp, 0

push 0
call print_placeholder

keyboard_loop:
    call wait_key
    push ax
    mov bl,al
    call simple_print
    cmp al,13
    jne keyboard_loop
    call newline
    je print_stack_values

print_stack_values:
    pop bx
    call simple_print
    cmp bx,0
    jne print_stack_values
    push 0
    call print_placeholder
    je keyboard_loop

jmp $

placeholder:
    db "ENTER: ",0

print_placeholder:
    call newline
    mov bx,placeholder
    call print_string
    ret

newline:
    mov ah, 0x0e 
    mov al, 10   
    int 0x10
    mov al, 13   
    int 0x10
    ret

wait_key:
    mov ah, 0
    int 0x16
    ret

%include "print_string.asm"


times 510-($-$$) db 0
dw 0xaa55 

qemu run result:

ENTER: Hello World
dlroW olleH

ENTER: this is a string
gnirts a si siht

CodePudding user response:

Save the value of the SP register before you start the keyboard_loop. Once you detect that the CR character has been entered (13h), then load that address and output the string from there. Just be sure to keep track of how many characters you pushed onto the stack and adjust the stack accordingly before you return.

A comment on the code:

You have this code at the end of your keyboard_loop:

  jne keyboard_loop
  call newline
  je print_stack_values

print_stack_values:

The je print_stack_values instruction is not necessary because the code will fall through to print_stack_values. Furthermore, there's no guarantee that the Equal flag will be set after your call to newline. In this particular case that's no problem because if the Equal flag is not set it will just fall through to `print_stack_values'.

You should either remove the je instruction, or change it to jmp short print_stack_values.

  • Related