1 ; intarith.asm show some simple C code and corresponding nasm code
2 ; the nasm code is one sample, not unique
4 ; compile: nasm -f elf -l intarith.lst intarith.asm
5 ; link: gcc -o intarith intarith.o
8 ; the output from running intarith.asm and intarith.c is:
10 ; c=a+b, a=3, b=4, c=7
11 ; c=a-b, a=3, b=4, c=-1
12 ; c=a*b, a=3, b=4, c=12
13 ; c=c/a, a=3, b=4, c=4
15 ;The file intarith.c is:
23 ; printf("%s, a=%d, b=%d, c=%d\n","c=5 ", a, b, c);
25 ; printf("%s, a=%d, b=%d, c=%d\n","c=a+b", a, b, c);
27 ; printf("%s, a=%d, b=%d, c=%d\n","c=a-b", a, b, c);
29 ; printf("%s, a=%d, b=%d, c=%d\n","c=a*b", a, b, c);
31 ; printf("%s, a=%d, b=%d, c=%d\n","c=c/a", a, b, c);
35 extern printf
; the C function to be called
37 %macro pabc
1 ; a "simple" print macro
39 .
str db %1,0 ; %1 is first actual in macro call
41 ; push onto stack backwards
42 push dword [c
] ; int c
43 push dword [b
] ; int b
44 push dword [a
] ; int a
45 push dword .
str ; users string
46 push dword fmt
; address of format string
47 call printf
; Call C function
48 add esp,20 ; pop stack 5*4 bytes
51 section .data
; preset constants, writeable
52 a: dd 3 ; 32-bit variable a initialized to 3
53 b: dd 4 ; 32-bit variable b initializes to 4
54 fmt: db "%s, a=%d, b=%d, c=%d",10,0 ; format string for printf
56 section .bss
; unitialized space
57 c: resd
1 ; reserve a 32-bit word
59 section .text
; instructions, code segment
60 global main
; for gcc standard linking
64 mov eax,5 ; 5 is a literal constant
65 mov [c
],eax ; store into c
66 pabc
"c=5 " ; invoke the print macro
71 mov [c
],eax ; store into c
72 pabc
"c=a+b" ; invoke the print macro
76 sub eax,[b
] ; subtract b
77 mov [c
],eax ; store into c
78 pabc
"c=a-b" ; invoke the print macro
81 mov eax,[a
] ; load a (must be eax for multiply)
82 imul
dword [b
] ; signed integer multiply by b
83 mov [c
],eax ; store bottom half of product into c
84 pabc
"c=a*b" ; invoke the print macro
88 mov edx,0 ; load upper half of dividend with zero
89 idiv dword [a
] ; divide double register edx eax by a
90 mov [c
],eax ; store quotient into c
91 pabc
"c=c/a" ; invoke the print macro
93 mov eax,0 ; exit code, 0=normal
94 ret ; main return to operating system