Sistemi di Calcolo

Corso di Laurea in Ingegneria Informatica e Automatica - A.A. 2017-2018

HomePage | Avvisi | Diario lezioni | Programma | Materiale didattico | Esami | Forum | Login

Lunedì 9 e giovedì 12 ottobre 2017 (Lezione 3 - 150 min) - Demetrescu/Coppa


Sessione pratica con spiegazioni:

Esempio 1: costrutto if

Calcolo del valore assoluto di un intero:

main.c
#include <stdio.h>

int myabs(int x);

int main() {
    printf("abs(0)=%d\n",  myabs(0));
    printf("abs(-7)=%d\n", myabs(-7));
    printf("abs(15)=%d\n", myabs(15));
    return 0;
}


myabs.c
int myabs(int x) {
    if (x<0) x = -x;
    return x;
}


Traduzione IA32:

myabs.s
# int myabs(int x) {
#    if (x<0) x = -x;
#    return x;
# }

# C equivalente:
# int myabs(int x) {  // x <-> eax
#    if (x>=0) goto E;
#    x = -x;
#  E:return x;
# }

.globl myabs

myabs:
    movl 4(%esp), %eax # eax <- primo parametro int
    cmpl $0, %eax      # if (x>=0) goto E;
    jge E              # salta a E se %eax >= $0
    negl %eax          # x = -x;
E:  ret                # E: return x;


Esempio 2: costrutto if

Calcolo del minimo di due short:

min.c
#include <stdio.h>

short min(short x, short y);

int main(){
    short m = min(-7, -22);
    printf("%hd\n", m);
    return 0;
}


min.c
short min(short x, short y) {
    if (x < y) return x;
    return y;
}


Traduzione IA32:

min.s
# short min(short x, short y) {
#     if (x < y) return x;
#     return y;
# }

# C equivalente:
# short min(short x, short y) {
#     if (x >= y) goto E;        # x <-> ax, y <-> cx
#     return x;
# E   return y;
# }

.globl min

min:
    movw 4(%esp), %ax
    movw 8(%esp), %cx
    cmpw %cx, %ax        # if (x >= y) goto E
    jge E
    ret                  #     return x;
E:  movw %cx, %ax
    ret


Esempio 3: costrutto while

Calcolo del fattoriale di un intero senza segno:

main.c
#include <stdio.h>

unsigned fact(unsigned);

int main(){
    unsigned f = fact(6);
    printf("%u\n", f);
    return 0;
}


fact.c
unsigned fact(unsigned n) {
    unsigned f = 1;
    while (n > 1) {
        f *= n;
        n--;
    }
    return f;
}


Traduzione IA32:

fact.s
# unsigned fact(unsigned n) {
#    unsigned f = 1;
#    while (n > 1) {
#        f *= n;
#        n--;
#    }
#    return f;
# }

# C equivalente:
# unsigned fact(unsigned n) {   # n <->ecx
#    unsigned f = 1;            # f <-> eax
# L: if (n <= 1) goto E;
#    f *= n;
#    n--;
#    goto L;
# E: return f;
# }

.globl fact

fact:
    movl 4(%esp), %ecx # carica parametro n in ecx
    movl $1, %eax      #    unsigned f = 1;
L:  cmpl $1, %ecx      # L: if (n <= 1) goto E;
    jbe E
    imull %ecx, %eax   #    f *= n;
    decl %ecx          #    n--;
    jmp L              #    goto L;
E:  ret                # E: return f;

Valid XHTML 1.0 Transitional :: Valid CSS :: Powered by WikkaWiki
Page was generated in 0.0537 seconds