Capstone: command-line calculator
| The goal | |
| Design | |
| Build steps |
The goal
Build a reverse-Polish-notation calculator: calc 3 4 + prints 7. It walks argv, pushes numbers on a stack, applies operators, and prints the final value. It uses argv parsing, a manual stack, integer division, and printing a number in decimal.
Design
The stack is an array of qwords in .bss with a top pointer in a register. Parsing argv: each argument is either an operator (+ - * /) or a number to convert with the classic multiply-by-ten loop. Printing converts the result back by repeated division by 10, storing remainders, then printing the digits in reverse:
section .bss
stack resq 64
section .text
; push: [top] = value, top++
; pop: top--, value = [top]
Build steps
Loop over argv from 1 to argc. For each argument, compare the first byte against +, -, *, /. If it matches and the argument is one character, pop two operands, compute, and push the result. Otherwise convert the string to a qword and push it. After the loop, pop the final value, convert to decimal digits into a buffer, and sys_write it with a newline. Test with 2 3 *, 10 4 -, and 100 7 / so you check the quotient path too.
Next: Capstone: hex editor
Article author: Arthur Isaev