Assembly programming

Friday, November 28, 2008 » programming

Today got some kind of feeling to turn it on and browsing through my old files. Just got some nostalgic feeling to going through my old projects, reading codes I have ever wrote and understood. This was my first PC during the university so it held old materials from that time, from the bachelor times.. So I've decided, I am going to renew and share my old code snippets or projects for fun to surf on these.
The first topic will be the next assembly code had to be written for credits in ASM: finding maximum element in an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
;*************************************************************************
; Finding maximum element (index returning)
; Compiler: NASM, tested on: Windows XP 
; Filename: maximum_searching.asm
; Creator: bana, created on: November, 2007
;*************************************************************************

global _maximum_searching
segment code use32 class=code

;*************************************************************************
; int maximum_searching(int* start_index , int n);
;*************************************************************************
  
  _maximum_searching:
  push ebp
  mov ebp,esp
  
  %define start_index dword [ss:ebp+8]; pointer to 1th item of array
  %define n dword [ss:ebp+12]         ; size of array
   
  mov eax,0                           ; INDEX
  mov ebx,0                           ; always shifting 4 byte, initial 0  
  mov esi,start_index                 ; loading 1th item into abstract MAX ( =edx )
  mov edx,[esi]
  
  mov ecx,n                           ; loop from N-1 (=ecx) stepping back by one
  cmp ecx,1
  jbe end.
   
  sub ecx,1
  c.
    add ebx,4
    cmp [esi+ebx],edx                 ; if CURR_ITEM (= [esi+ebx] shifted) > MAX (=edx)
    ja larger.
    jbe smaller.
    larger.                           ;      CURR_ITEM = MAX (=larger)
      mov edx,[esi+ebx]
      mov eax,n                       ;      INDEX = ( N - position_of CURR_ITEM ) 
      sub eax,ecx
    smaller.                          ; otherwise nothing
  loop c.
  
  end.
  pop ebp
  ret                                 ; returning with index of largest item (eax)
  %undef start_index
  %undef n

An usage of asm file in sort of C++ pseudo-code, maximum sorting.

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
  int n = 10;
  int t[n] = {15,34,782,9873,56,23,15,31,56,98};
  
  int max_index = 0;
  
  for(int i = n ; i > 0 ; --i)
  {
    max_index = maximum_searching(t,i);
    replace(t,max_index,i-1);	
  }
}