Search code examples
cassemblycodeblocksinline-assembly

Assembler code in C adding 1 to input and to power x times


I have to write some asm("code") in C using CodeBlocks. I need to increment input value 'a' by one and then power the result like this a * a * a. Where incrementing and power value a*a is easy, the another power powers the result of previous power. For ex. 2 * 2=4 then 4 * 4=16 My current code:

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


int main(){
short int a,b;
scanf("%hu",&a);
asm("mov %1, %%ax\n\t"
    "inc %%ax\n"
    "mul %%ax\n"
    "mov %%ax, %0"
    :"=r" (a)
    :"r" (a), "r" (b)
    );
    printf("%d\n", a);
    return 0;
}

Solution

  • Not the best or simplest or cleanest way but this works for me. It add 1 to input value and then do power the value 2 times.

    #include <stdio.h>
    #include <stdlib.h>
    int main(){
    int a, b,c=1;
    scanf("%i",&a);
    asm( "addl %%ebx, %%eax;" : "=a" (a) : "a" (a) ,  "b" (c) );
    asm( "imul %%ebx, %%eax;" : "=a" (b) : "a" (a) ,  "b" (a) );
    asm( "imul %%ebx, %%eax;" : "=a" (b) : "a" (a) ,  "b" (b) );
    printf("%d\n", b);
    return 0;
    }