06-scanf.asm 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. ;;; Required packages: nasm, gcc
  2. ;;; compile commands:
  3. ;;; nasm -f elf 06-scanf.asm -o bin/06-scanf.o
  4. ;;; gcc -m32 -o bin/06-scanf bin/06-scanf.o
  5. %define SYSCALL_EXIT 1 ; system call sys_exit
  6. %define INT32_BYTES_SIZE 4
  7. %define FLOAT32_BYTES_SIZE 4
  8. %define STRING_BUFFER_SIZE 32
  9. section .data
  10. questionString db "Please enter a string.", 0xa, 0x0
  11. questionInt32 db "Please enter any integer number.", 0xa, 0x0
  12. questionFloat32 db "Please enter any decimal number.", 0xa, 0x0
  13. prompt db "> ", 0x0
  14. resultMessage db "Entered: string %s, int %d, float %f", 0xa, 0x0
  15. scanInt32Fmt db "%d", 0x0
  16. scanFloat32Fmt db "%f", 0x0
  17. scanStringFmt db "%s", 0x0
  18. section .bss
  19. inum resb INT32_BYTES_SIZE
  20. fnum resb FLOAT32_BYTES_SIZE
  21. text resb STRING_BUFFER_SIZE
  22. section .text
  23. extern scanf
  24. extern printf
  25. global main
  26. main:
  27. call printStringPrompt
  28. call scanString
  29. call printInt32Prompt
  30. call scanInt32
  31. call printFloat32Prompt
  32. call scanFloat32
  33. call printMessage
  34. mov eax, SYSCALL_EXIT
  35. mov ebx, 0
  36. int 0x80
  37. ret
  38. scanInt32:
  39. push inum
  40. push scanInt32Fmt
  41. call scanf
  42. add esp, 8
  43. ret
  44. scanFloat32:
  45. push fnum
  46. push scanFloat32Fmt
  47. call scanf
  48. add esp, 8
  49. ret
  50. scanString:
  51. push text
  52. push scanStringFmt
  53. call scanf
  54. add esp, 8
  55. ret
  56. printInt32Prompt:
  57. push questionInt32
  58. call printf
  59. add esp, 4
  60. push prompt
  61. call printf
  62. add esp, 4
  63. ret
  64. printFloat32Prompt:
  65. push questionFloat32
  66. call printf
  67. add esp, 4
  68. push prompt
  69. call printf
  70. add esp, 4
  71. ret
  72. printStringPrompt:
  73. push questionString
  74. call printf
  75. add esp, 4
  76. push prompt
  77. call printf
  78. add esp, 4
  79. ret
  80. printMessage:
  81. sub esp, 8 ; reserve stack for a float64 (%f requires float64 in printf)
  82. mov ebx, fnum
  83. fld DWORD [ebx] ; load float32 in current stack place (32 bits)
  84. fstp QWORD [esp] ; store float64 (8087 does the conversion from float32 internally)
  85. push DWORD [inum]
  86. push text
  87. push resultMessage
  88. call printf
  89. add esp, 20
  90. ret