Posts

Showing posts with the label Assembly

Simplest Fibonacci Assembly Code

Image
Tl;Dr There is an insanely cool, simple and elegant way to calculate Fibonacci numbers in assembly using only 2 opcodes!

Full disclosure: this post is inspired by chapter two of the book "xchg rax, rax".
Fibonacci Numbers Just a simple review: Fibonacci Numbers are calculated with the formula below.


So for example to get the 3'rd Fibonacci number, we need to sum the 2nd and 1st Fibonacci numbers.
The Code 👨‍💻👩‍💻 Behold! Below is the most elegant code you will ever see for in assembly


Source available here.
Explanation🧠 The magic happens in the XADD opcode which is an "xchg (exchange)" and "add"  operation in one opcode. It works exactly as you would expect: first exchange the two operands, and then add them saving the result to the first operand. Official Intel documentation here.

Next, the "loop" opcode changes the code flow to jump back and re-execute the xadd opcode multiple times.
Understanding ✔ To completely understand why and ho…