Using Inline Assembly at Timus Online Judge


Timus online judge is my favorite.  There are many compilers that are on windows platform, for example, Visual Studio.

Does the judge accept program that embeds inline assembly ? The answer is yes. For problem A+B (The easiest problem on earth, which exists for testing the system)

http://acm.timus.ru/problem.aspx?space=1&num=1000

We can write C/C++ solution with inline assembly (32-bit).

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h> 
 
int main() {
  int a, b, t;
  scanf("%d %d", &a, &b);
  __asm {
     mov eax, a
     add eax, b
     mov t, eax
  }
  printf("%d", t);
  return 0;
}
#include <stdio.h> 

int main() {
  int a, b, t;
  scanf("%d %d", &a, &b);
  __asm {
     mov eax, a
     add eax, b
     mov t, eax
  }
  printf("%d", t);
  return 0;
}

In FreePascal/Delphi, the add function couldn’t be simpler.

program p1000;
{$APPTYPE CONSOLE}

var
  a, b: integer;

function add(a, b: integer): integer;
asm
  add eax, edx
end;

begin
  read(a, b);
  write(add(a, b));
  readln;
end.

The first parameter is passed as the 32-bit register eax and the second is being passed as edx. The integer value is returned as eax.

Maybe this isn’t useful in writing 32-bit assembly, but in some cases, where the assembly is far better. For example, in computing the value of trunc(log2(some integer)), the following inline assembly function is the fastest.

function log2(a: integer): integer; assembler;
asm
  bsr eax, eax
end;

The above log2 takes the integer parameter as store it in eax. The instruction bsr scans from left to right the first filled-bit and returns its index in the register eax which is the returned-result of this function. In binary, the index is the trunc-integer part of the value log2(a).

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
355 words
Last Post: Ackermann Function
Next Post: Finally Block in C#

The Permanent URL is: Using Inline Assembly at Timus Online Judge

Leave a Reply