Detailed explanation and alternative code implementation for very large bitmaps below.
bool lut6(uint64_t bitmap, bool in[6])
{
int mapbit = 0;
if (in[0]) mapbit += 1;
if (in[1]) mapbit += 2;
if (in[2]) mapbit += 4;
if (in[3]) mapbit += 8;
if (in[4]) mapbit += 16;
if (in[5]) mapbit += 32;
if (in[6]) mapbit += 64;
return ((bitmap >> mapbit) & 1) != 0;
// Above calculation is often faster due to compiler optimization
// return (bitmap & (1 << mapbit)) != 0;
}| Function: | ||
|---|---|---|
| Hex: | ||
| Bin: | ||
A Boolean function is a combination of the inputs. Creating any Boolean function is a matter of selecting all the combinations of inputs that will give a 1 as output. Selecting which input combinations should result in a 1 output can be written as a bitmap. That bitmap can be used to calculate the output from the inputs, where each bit in the bitmap represents an input combination. Each bit in the bitmap is one specific row of the truth-table.
For example, a two-input Boolean function has four possible combinations 0…3:
| index | in-1 | in-0 | AND | OR | XOR |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 |
| 1 | 0 | 1 | 0 | 1 | 1 |
| 2 | 1 | 0 | 0 | 1 | 1 |
| 3 | 1 | 1 | 1 | 1 | 0 |
The AND-gate's output is only 1 when both inputs are 1.
The AND-gate can be described by reading the output column as a bitmap.
Read from top-to-bottom and written from right-to-left becomes 1 0 0 0.
The bitmap can be written as a value: 0b1000 = 0x8.
Similarly, an OR-gate becomes 0x7 (0b0111) and an XOR-gate becomes 0x6 (0b0110).
Calculating the output on basis of inputs becomes a question of selecting the correct bit in the bitmap.
Each input can be interpreted as a bit in a binary value.
That binary value is just the index of the row in above table.
As can be seen, the index value is represented in binary by the inputs on that row.
And so, each bit in the binary input value has a weight 2N according to its position N, with position zero (0) being the rightmost position.
The sum of weights is the value of the index, the row in the truth-table and the bit position in the bitmap.
Extending the same idea to three, four and more inputs just makes a larger bitmap.
The bitmap can be a simple variable in a program of appropriate size to hold the required number of bits.
There is an alternative if you do not have anything larger than uint32_t.
You can pass the bitmap as an array of 32-bit values and index that with the most significant bits.
You split the bitmap from least to most significant bits in increasing indices and use code like:
bool lut7_32(uint32_t bitmap[4], bool in[7])
{
int mapbit = 0;
if (in[0]) mapbit += 1;
if (in[1]) mapbit += 2;
if (in[2]) mapbit += 4;
if (in[3]) mapbit += 8;
if (in[4]) mapbit += 16;
int idx = 0;
if (in[5]) idx += 1;
if (in[6]) idx += 2;
return ((bitmap[idx] >> mapbit) & 1) != 0;
}