DEV Community

Gealber Morales
Gealber Morales

Posted on • Originally published at gealber.com

Challenge #31

This challenge can be an easy one if you start with the Optimizing MSVC 2012 x64
assembly code example, instead of the Optimizing MSVC 2010 x86. The problem with the Optimizing MSVC 2010 x86 example, is the use of FPU Register Stack which makes kinds of hard to follow the logic. If you want to know more about floating points, I highly recommend you read the chapter from Reverse Engineering for Beginners, from the same author of the challenge. At the end of the articles, I'll link other sources as well. As always the code can be found in the original website.

In case you are kind of lost and don't have an idea of what to consult to learn more about floating points, take a look at the Bibliography.

Analysis

The code we need to analyze has three float constants, 1.0, 0.001, and 0.5. These constants are defined in the following lines

__real@3fe0000000000000 DQ 03fe0000000000000r ;; 0.5
__real@3f50624dd2f1a9fc DQ 03f50624dd2f1a9fcr ;; 0.001
__real@3ff0000000000000 DQ 03ff0000000000000r ;; 1.0

Enter fullscreen mode Exit fullscreen mode

Apart from this, the logic is straightforward, and not too complicated. Here's the code in C language:

double f(double a)
{
    double cur = 1.0;
    while (cur*cur - a <= 0.001) {
        cur = (a / cur + cur) * 0.5; // same as dividing by 2
    }

    return cur;
}
Enter fullscreen mode Exit fullscreen mode

Printing the result of calling this function, you can notice that we will receive basically a / 2 + 0.5.

Bibliography

  1. Chapter Code Patterns, Floating unit from beginners.re.
  2. Intel Manual. Volume 1, Chapter 8 Programming with the x87 FPU.

Also, the author of the challenge recommends getting familiar with the Forth Programming Language, it is not to get a super pro on this programming language, it's just to get familiar with the way of programming with a stack-based approach. This language plays also an inspiration in the Fift Programming Language of the TON Blockchain.

Top comments (0)