Gerd Isenberg wrote:Rein Halbersma wrote:
I have been doing some very elementary exercises (mostly in Excel and by hand) with 16-bit integers in order to see what is going on.
1)If e.g. I have n scattered bits and want to form an n-bit index for the occupancy of those bits, I simply make an 16xn multiplication table. Every (i,j) entry has as value (i+j-(16-n)). This is just the fact that multiplication of powers of 2 is equal to addition of their exponents.
2)To find a magic, what I do is to look for a sequence of rows (out of the 16 available) in such a way that every number 0:n-1 occurs exactly once in the combined rows, and that every column has a unique number out of 0:n-1 on those selected row.
3) With carry effects, things are more subtle and I am trying to understand the patterns that happen then.
About your multiplication table, I don't get that. Can you elaborate a bit more on it, e.g. with some sample pattern and numbers for a mathematical patzer?
Hi Gerd,
OK, it seems that I can't add an Excel-attachment on this forum?
Here's a 32-bit example where the LSB is bit 0 and the MSB is bit 31. I wish to index a bitmask with the following bits: 8,9,10,16,17,18,24,25 and 26. This means I AND my occupancy bitboard with the configuration 0x7070700 = 2^8 + ... + 2^26. I use the following magic: 0x82001 = 2^19 + 2^13 + 2^0, so the magic has only 3 active bits.
index = (occupancy & mask) & magic >> (32-9)
You can check that with mask = 0x7070700 and magic = 0x82001 this gives a 9-bit index. To check this with a multiplication table:
Code: Select all
8 9 10 16 17 18 24 25 26
0 -15 -14 -13 -7 -6 -5 1 2 3
13 -2 -1 0 6 7 8 14 15 16
19 4 5 6 12 13 14 20 21 22
The above table shows the active bits in the mask (columns) and in the magic (rows). The entries in the table are the active bits in the index (entry_ij = i+j-(32-9)). Only bits 0...8 are used in the actual index.
Rowwise, notice that bit 0 in the magic fills bits 1,2,3 in the index, bit 13 in the magic fills bits 0,6,7,8 and bit 19 in the magic fills bits 4,5,6. Columnwise, notice that all bits in the mask almost uniquely fill a bit in the index.
There is only a single overlap: bit 6 in the index is filled by bits 0 and 13 in the magic when bits 16 and 10, respectively, are set in the mask. Fortunately, bit 10 in the mask is also uniquely filling bit 0 in the index. This means that the carry of bit 6 in the index can freely propagate to bits 7 and 8 since bit 0 in the index marks whether there has been a carry forward in the index.
It's reasoning like this that I would like to generalize when generating magics for arbitrary bitmasks.
Rein