Compare 2 numbers with assembly
I have the following code. And I want to execute assembly code as below:
int main(void)
{
int x = 10;
int i=0;
label1:
asm (.....) // code to add here: if i>=x then jump to label2
printf("%d\n",i);
i++;
asm (.....) // code to add here: jump to label 1
label2:
printf("out\n");
}
My computer is x86 and operating system is Ubuntu 12
source to share
First, grab yourself a list of x86 operating codes, they are easy to find on the internet.
The function asm()
follows this order:
asm ( "assembly code"
: output operands /* optional */
: input operands /* optional */
: list of clobbered registers /* optional */
);
Secondly, one major problem you are experiencing is that you cannot "jump" to label C, you need to make the label a shortcut to "assembly" in order to be able to jump to it. eg:
int main()
{
asm("jmp .end"); // make a call to jmp there
printf("Hello ");
asm(".end:"); //make a "jumpable" label
printf("World\n");
return 0;
}
The output of this program is just "Peace" when we jump over "Hello". Here's the same example, but with a comparative jump:
int main()
{
int x = 5, i = 0;
asm(".start:");
asm("cmp %0, %1;" // compare input 1 to 2
"jge .end;" // if i >= x, jump to .end
: // no output from this code
: "r" (x), "r" (i)); // input are var x and i
printf("Hello ");
i++;
asm("jmp .start;");
asm(".end:");
printf("World\n");
return 0;
}
source to share
I don't remember the semantics of using assembler inside c, but usually when you compare a number in assembler, you subtract the numbers from each other. If they were the same number, the zero bit will be set, so you can conditionally jump. Remember to use the correct registers according to the size of the int.
A very crude example of code (this is not ok and it has been many years since I wrote the assembler):
#load value to compare against into BX
#load number to check into AX
CMP AX, BX
JE label
updated: changed SUB to CMP as suggested by @harold
source to share