Skip to main content
Mod Removes Wiki by Doorknob
added 1008 characters in body
Source Link
xnor
  • 149.7k
  • 26
  • 287
  • 676

Store lookup tables as magic numbers

Say you want to hardcode a Boolean lookup table, like which of the first twelve English numbers contain an en.

0: False 1: True 2: False 3: False 4: False 5: False 6: False 7: True 8: False 9: True 10:True 11:True 12:False 

0: True 1Then, you can implement this lookup table concisely as:

3714>>i&1 

with the resulting 0 or 1 being equal to False to True.

The idea is that the magic number stores the table as a bitstring bin(3714) = 0b111010000010, with the n-th digit (from the end) corresponding the the nth table entry. We access the nth entry by bitshifting the number n spaces to the right and taking the last digit by &1.

This storage method is very efficient. Compare to the alternatives

n in[1,7,9,10,11] '0111010000010'[n]>'0' 

You can have your lookup table store multibit entries that can be extracted like

 340954054>>4*n&15 

to extract the relevant four-bit block.

Store lookup tables as magic numbers

Say you want to hardcode a Boolean lookup table, like which of the first twelve English numbers contain an e.

0: True 1:

Store lookup tables as magic numbers

Say you want to hardcode a Boolean lookup table, like which of the first twelve English numbers contain an n.

0: False 1: True 2: False 3: False 4: False 5: False 6: False 7: True 8: False 9: True 10:True 11:True 12:False 

Then, you can implement this lookup table concisely as:

3714>>i&1 

with the resulting 0 or 1 being equal to False to True.

The idea is that the magic number stores the table as a bitstring bin(3714) = 0b111010000010, with the n-th digit (from the end) corresponding the the nth table entry. We access the nth entry by bitshifting the number n spaces to the right and taking the last digit by &1.

This storage method is very efficient. Compare to the alternatives

n in[1,7,9,10,11] '0111010000010'[n]>'0' 

You can have your lookup table store multibit entries that can be extracted like

 340954054>>4*n&15 

to extract the relevant four-bit block.

Source Link
xnor
  • 149.7k
  • 26
  • 287
  • 676

Store lookup tables as magic numbers

Say you want to hardcode a Boolean lookup table, like which of the first twelve English numbers contain an e.

0: True 1: