![]() |
![]() |
|
|
Boolean Lookup Tables
Generate any boolean function using a bitmap LUT
Boolean logic can be surprising in how many ways there are to write one and the
same thing. Some are easier than others and programming with many inputs in
software can be a challenge.When dealing with four, five or more inputs, how do you code your Boolean equations? How can you make sure that your if() statements do not
drown in variable names and operators like || and
&&?TLDR or TLSU or TLTB or TLDC: give me the code to make my own LUT bitmaps. One way is to use a generic method using a bitmap that describes all the cases where your Boolean functions should be true. The bitmap is used as a LookUp Table, a LUT, and each bit in the bitmap represents one combination of the input variables. A Boolean LUT function with six inputs can be implemented like:
How the LUT worksA 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 (index 0…3):
Calculating the output on basis of inputs becomes a question of selecting the correct bit in the bitmap (the (bitmap >> mapbit) & 1 statement).
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 (i.e. calculating the value of
mapbit).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. Although, a practical limit is usually around eight inputs. A self-hosted HTML file lut.html has all code embedded to make your bitmap LUT. It also includes the outline of a function that will calculate the proper output based in the inputs. You can adapt that as you please. You can run it from this site or you can download it and run it locally on your computer. No external dependencies required. Inspired to write about it while hacking LinuxCNC and working on components. Specifically, the lut5 component uses this Boolean function method to be a generic component to handle any possible 2..5-input Boolean function.
Posted: 2026-09-07 |
| Overengineering @ request | Prutsen & Pielen since 1982 |