update repository
[cmdllinux.git] / bash_n_examples / lang / nasm / intarith.asm
blobe3209ec286c896377beb96578301d8d0bb2882d4
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
6 ; run: intarith
8 ; the output from running intarith.asm and intarith.c is:
9 ; c=5 , a=3, b=4, c=5
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:
16 ; /* intarith.c */
17 ; #include <stdio.h>
18 ; int main()
19 ; {
20 ; int a=3, b=4, c;
22 ; c=5;
23 ; printf("%s, a=%d, b=%d, c=%d\n","c=5 ", a, b, c);
24 ; c=a+b;
25 ; printf("%s, a=%d, b=%d, c=%d\n","c=a+b", a, b, c);
26 ; c=a-b;
27 ; printf("%s, a=%d, b=%d, c=%d\n","c=a-b", a, b, c);
28 ; c=a*b;
29 ; printf("%s, a=%d, b=%d, c=%d\n","c=a*b", a, b, c);
30 ; c=c/a;
31 ; printf("%s, a=%d, b=%d, c=%d\n","c=c/a", a, b, c);
32 ; return 0;
33 ; }
35 extern printf ; the C function to be called
37 %macro pabc 1 ; a "simple" print macro
38 section .data
39 .str db %1,0 ; %1 is first actual in macro call
40 section .text
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
49 %endmacro
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
61 main: ; label
63 lit5: ; c=5;
64 mov eax,5 ; 5 is a literal constant
65 mov [c],eax ; store into c
66 pabc "c=5 " ; invoke the print macro
68 addb: ; c=a+b;
69 mov eax,[a] ; load a
70 add eax,[b] ; add b
71 mov [c],eax ; store into c
72 pabc "c=a+b" ; invoke the print macro
74 subb: ; c=a-b;
75 mov eax,[a] ; load a
76 sub eax,[b] ; subtract b
77 mov [c],eax ; store into c
78 pabc "c=a-b" ; invoke the print macro
80 mulb: ; c=a*b;
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
86 diva: ; c=c/a;
87 mov eax,[c] ; load c
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