If I have a truth table, is there a way of determining the bitwise expression I need for that truth table?
binary, bit-manipulation, c
Solution
Use Karnaugh Map - there is a solver available online. Pick "three values", enter the expected results for all eight combinations, and use the expression the solver produces:
F(m, p, n) = (p & !n) | (m & n)
EDIT : You can expand this solution to do the whole byte at once, rather than doing it one bit at a time, by using the `~` bitwise NOT operator:
result = (mask & new) | (~mask & previous);
Problem
I am attempting to do the following in c: ``` unsigned int mask; unsigned int previous; unsigned int new; unsigned int out; for( int i = 0; i < 8; ++i ) { bool bit_set = GET_BIT( mask, i ); // If the mask bit is true, use the new bit, otherwise use the previous bit SET_BIT( out, i, GET_BIT( bit_set ? new : previous, i ) ); } ``` However I think there may be an easier and quicker way using bitwise operations. I have the truth table but I don't know how to get the expression I need. Truth table is: ``` m | p | n | o 0 | 0 | 0 | 0 1 | 0 | 0 | 0 0 | 1 | 0 | 1 1 | 1 | 0 | 0 0 | 0 | 1 | 0 1 | 0 | 1 | 1 0 | 1 | 1 | 1 1 | 1 | 1 | 1 ``` How would I go about working this out?