int double0(int num)
{
return num * 2;
}
int double1(int num)
{
return num << 1;
}
Recently I've been playing 7 Billion Humans and Human Resource Machine which are games filled with programming puzzles that you solve using a visual interface like Scratch, however, when you copy and paste the code, you'll find that it looks more like assembly. One of the puzzles in it is to find the x and y co-ordinates of a position in an array, given its width. If you were writing the function in a high level language, you might come up with something that looks like this:
void getXandYfromIndex(int index, int width, int& x, int& y)
{
x = index % width;
y = index / width;
}
void getXandYfromIndex2(int index, int width, int& x, int& y)
{
std::div_t div = std::div(index, width);
x = div.rem;
y = div.quot;
}
Looking up the documentation for idiv, it says: "Divides the operand by the value stored in EAX. The quotient result of the division is stored into EAX. The remainder is placed in EDX." In the code from before we see that our variable _x$ gets stored in EAX after the division, overwriting the quotient. I tried swapping the order of the operations to see if the compiler could figure it out that way, but I got similar results.
After a bit of thinking, I came up with the following code:
push ebp
mov ebp, esp
mov eax, DWORD PTR _index$[ebp]
cdq
idiv DWORD PTR _width$[ebp]
mov ecx, DWORD PTR _y$[ebp]
mov DWORD PTR [ecx], eax
mov eax, DWORD PTR _x$[ebp]
mov DWORD PTR [eax], edx
pop ebp
ret 0