Reputation: 4487
I've got (binary) matrices represented by uint64_t (from C++11). And I'd like to be able to efficiently map from any column into first rank. For example
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
uint64_t matrice = 0x4040400040400040uLL;
uint64_t matrice_2 = map(matrice, ColumnEnum::Column2);
1 1 1 0 1 1 0 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
matrice_2 contains 0xED00000000000000uLL;
Upvotes: 3
Views: 442
Reputation: 8143
Great question. I really enjoyed the hacking. Here is my solution:
uint64_t map(uint64_t x, int column)
{
x = (x >> (7 - column)) & 0x0101010101010101uLL;
x = (x | (x >> 7)) & 0x00FF00FF00FF00FFuLL;
x = (x | (x >> 14))& 0x000000FF000000FFuLL;
x = (x | (x >> 28))& 0x00000000000000FFuLL;
return x << 56;
}
A working example can be found at ideone, where the call is really map(matrice, ColumnEnum::Column2)
.
Upvotes: 3
Reputation: 153792
A nice little riddle. Here is a reasonably readable version:
matrice = (matrice >> (8ull - column)) & 0x0101010101010101ull;
uint64_t result(( ((matrice >> 0ul) & 0x01ull)
| ((matrice >> 7ul) & 0x02ull)
| ((matrice >> 14ull) & 0x04ull)
| ((matrice >> 21ull) & 0x08ull)
| ((matrice >> 28ull) & 0x10ull)
| ((matrice >> 35ull) & 0x20ull)
| ((matrice >> 42ull) & 0x40ull)
| ((matrice >> 49ull) & 0x80ull)) << 56ull);
Upvotes: 3
Reputation: 24347
First define bitmask for every column:
uint64_t columns[8] = {
0x8080808080808080uLL,
0x4040404040404040uLL,
//...
0x0101010101010101uLL
};
by applying column bitmask to your "matrice" you get only this column:
uint64_t col1 = matrice & columns[1]; // second column - rest is empty
by shifting you can get only first column case:
uint64_t col0 = (col1 << 1); // second column - rest is empty
// ^ this number is just zero based index of column,,,
Now first bit is on right place - just set the next 7 bits:
col0 |= (col0 & (1 << 55)) << 7; // second bit...
// ....
Or just use std::bitset<64>
, I would do....
Upvotes: 1