Friday, May 16, 2025

A leap year check in three instructions

 https://hueffner.de/falk/blog/a-leap-year-check-in-three-instructions.html

With the following code, we can check whether a year 0 ≤ y ≤ 102499 is a leap year with only about 3 CPU instructions:

bool is_leap_year_fast(uint32_t y) {
    return ((y * 1073750999) & 3221352463) <= 126976;
}

How does this work? The answer is surprisingly complex. This article explains it, mostly to have some fun with bit-twiddling; at the end, I'll briefly discuss the practical use.

 

Bonus link:

That article links out to this site several times that lets you input high level code like C/Ruby/Javascript/etc and see the compiled/assembly output.

https://godbolt.org/z/PWs8saMYd

No comments:

Post a Comment