Challenge #10

Here I’m again, this time with the 10th challenge from challenge.re. This one it’s quite short, and according to the author, also tricky, let’s see what we have in this case.

Analysis

Assembly code to understand

f:
    lea     eax, [rdi-1+rsi]
    neg     esi
    and     eax, esi
    ret

We have basically 4 operations, including the ret one. First we have two arguments, one in rdi and the other one in rsi. Looking at the use of them, we can assume they are numbers. Let’s assume that both of them are 32 bits integers, given that rdi-1+rsi its store in the eax register, which is a 32 bits register.

The next instruction it’s a negation of the number in rsi, followed by and AND operation between this negation with the first number. This it’s confusing when you read all this without a real number examples. Let’s put that into C code.

in f(int a, int b)
{
    return (a - 1 + b) & (~ b);
}

Still confusing….🤔…no idea what’s this? Reading the description of the problem, it says:

This code snippet is short, but tricky. What does it do? It’s used heavily in low-level programming and is well-known to many low-level programmers. There are several ways to calculate it, and this is the one of them.

So…still no idea, this doesn’t ring a bell to me. If anyone knows about it, let me know, I’m curious about what this computes.