반복문 : for , while
1.while
int cnt =10;
int main()
{
while(cnt>0){
printf("%d\n",cnt);
cnt --; // inc(++), dec(--)
}
return 0;
}
2.for문
int cnt =10;
int main()
{
for( ; cnt > 0 ; cnt --){
printf("%d\n",cnt);
cnt --; // inc(++), dec(--)
}
return 0;
}
while 이랑 for문은 문장 구조만 다르지 실행되는 방식은 똑같다
extern printf
segment .data
prompt_int db '%d',10,00
cnt dd 10
segment .text
global main
main:
while:
cmp dword [cnt], 0
jle end
push dword [cnt]
push prompt_int
call printf
dec dword [cnt]
jmp while
end:
[실습]
-문자열을 입력받아서 거꾸로 출력하는 어셈블리 프로그램을 작성
-scanf, gets, fgets, ...
1. 알고리즘
문자열을 배열로 입력받아서 반복문으로 출력한다
C코드
char buffer[1024];
int length = 0;
int i = 0;
int main() {
gets ( buffer );
while( buffer[length] != '\0' ) {
len++;
}
len--;
for( i = length; i >= 0; i-- ) {
printf("%c", buffer[i]);
}
printf("\n");
return 0;
}
만약 abc를 입력받는다고 생각하면
1.buffer에 abc를 저장한다
buffer의 값이 null 값이 나올때 까지 len을 더해준다
0,1,2,null
a,b,c,
그럼 len이 3이 된다
len을 -- 해서 1을 빼주고
2에서
(i=2 이고 i 가 0보다 크거나 같을때 ,i --)
i가 2일때 printf buffer[2] -> c
i가 1일때 printf buffer[1] -> b
i가 0일때 printf buffer[0] -> a
extern printf
extern scanf
segment .data
string1 dd '%c',10,00
string2 dd 'input:',00
input dd '%s',10,00
newline dd '',10,00
length dd 0
i dd 0
segment .bss
buffer resb 1024
segment .text
global main
main:
push string2
call printf
push buffer
push input
call scanf
while:
mov eax,dword [length]
cmp dword [buffer+eax], 0
je then
inc dword [length]
jmp while
then:
dec dword [length]
mov ebx,dword [length]
mov dword [i],ebx
then1:
cmp ebx ,0
jl end
mov edx, dword [buffer+ebx]
push edx
push string1
call printf
dec ebx
jmp then1
end:
push newline
call printf
실행 결과
[실습]
-정수 5개를 배열로 입력받아서 배열의 총합을 출력하는 프로그램을 작성
#include <stdio.h>
int main()
{
int i, arr[5],sum;
printf("input:");
for(i=0; i<=4; i++) {
scanf("%d", &arr[i]);
}
sum=arr[0];
for(i=1; i<5; i++){
sum += arr[i];
}
printf("sum:%d",sum);
return 0;
}
extern printf
extern scanf
segment .data
input db '%d', 00
output db '%d', 10, 00
segment .bss
arr resd 10
i resd 1
sum resd 1
segment .text
global main
main:
mov eax, 0
mov dword [sum], eax
mov dword [i], eax
while:
mov eax, dword [i]
cmp eax, 5
je then
mov edx, arr
mov ecx, dword [i]
imul ecx, 4
add edx, ecx
push edx
push input
call scanf
inc dword [i]
jmp while
then:
mov eax, 0
mov dword [i], eax
while1:
mov eax, dword [i]
cmp eax, 5
je end
mov ecx, dword [i]
imul ecx, 4
mov edx, 0
mov edx, dword [arr + ecx]
add dword [sum], edx
inc dword [i]
jmp while1
end:
push dword [sum]
push output
call printf
'시스템 해킹' 카테고리의 다른 글
[시스템 해킹] 배열 지역 변수로 구현하기 (0) | 2018.01.27 |
---|---|
[시스템 해킹] 어셈블리 함수 표현 (Stack) (0) | 2018.01.23 |
[시스템 해킹] 어셈블리 형변환, 분기문 (0) | 2018.01.17 |
[시스템 해킹] 어셈블리 사칙연산 (0) | 2018.01.16 |
[시스템 해킹] 주소 Vs 메모리,레지스터 (0) | 2018.01.15 |