OK, let's consider a 64-bit number, with its bits forming a 8x8 table.
E.g.
0 1 1 0 1 0 1 0 0 1 1 0 1 0 1 1 0 1 1 1 1 0 1 0 0 1 1 0 1 0 1 0 1 1 1 0 1 0 1 0 0 1 1 0 1 0 1 0 0 1 1 0 1 1 1 0 0 1 1 0 1 0 1 0
written as
a b c d e f g h
----------------
0 1 1 0 1 0 1 0
0 1 1 0 1 0 1 1
0 1 1 1 1 0 1 0
0 1 1 0 1 0 1 0
1 1 1 0 1 0 1 0
0 1 1 0 1 0 1 0
0 1 1 0 1 1 1 0
0 1 1 0 1 0 1 0
Now, what if we want to isolate JUST e.g. column d (00100000
) (or any row/diagonal for that matter) ?
Can this be done? And if so, how?
HINTS :
(a) My main objective here - though not initially mentioned - is raw speed. I'm searching for the fastest algorithm around, since the "retrieval" function is being performed some millions of times per second.
(b) This is what comes closer to what I mean : https://www.chessprogramming.org/Kindergarten_Bitboards
Here's a solution with only 4 main steps:
It works like this:
The magic number is chosen to copy only the needed bits and let the rest fall into unused places / overflow over the number. The process looks like this (digits are bit "IDs", rather than the number itself):
If you add the
const
keywords, assembly becomes quite nice actually:No branching, no external data, around 0.4ns per calculation.
Edit: takes around 6th of the time using NPE's solution as baseline (next fastest one)