Category Archives: Assembly

Add integer between x and y by gcc inline asm code

Write a C function that adds integers between x and y, y >= x, using assembly inline

#include <stdio.h>
#include <stdlib.h>

/*return x+(x+1)+(x+2)+(x+3)+...+y*/

int asm_sum(int x, int y)
{
        int ret = 0;

        __asm__ (   "loop:addl %1, %0\n\t"
                    "inc %1\n\t"
                    "cmp %2, %1\n\t"
                    "jle loop"
                    :"+r"(ret)
                    :"r"(x), "r"(y)
                 );
        return ret;
}

int main()
{
        int x = 6;
        int y = 10;

        printf("asm_sum(%d, %d) return %d\n", 
               x, y, asm_sum(x,y));
        
        //output: asm_sum(6, 10) return 40

        return 0;
}
Advertisements

My_Substring: c code vs gcc inline assembly code


#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static inline char * sub_str(char *dest, char *src, int s_idx, int edix)
{
    int length = edix - s_idx + 1;
    int i;
    
    for(i = 0; i < length; i++)
    {
        *(dest + i) = *(src + s_idx + i);
    }
    *(dest + length) = '\0';
}

static inline char * asm_sub_str(char *dest, char *src, int s_idx, int edix)
{
    __asm__ __volatile__(   "cld\n\t"
                            "rep\n\t"
                            "movsb\n\t"
                            "xor %%al, %%al\n\t"
                            "stosb"
                            :
                            :"S"(src + s_idx), "D"(dest), "c"(edix - s_idx + 1)
                        );
}

int main(int argc, char *argv[])
{
    char* my_string = "hello world";
    char my_sub_string[100], asm_my_sub_string[100];
    sub_str(my_sub_string, my_string, 0, 5);
    asm_sub_str(asm_my_sub_string, my_string, 0, 5);
}