title: Truth tables in code? How to structure state machine?
body: <p>I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.</p>
  
  <p>My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.</p>
  
  <p>I was thinking I would like to access my truth table like so:</p>
  
  <pre><code>u8 newState[] = decisionTable[input1][input2][input3][input4];
  </code></pre>
  
  <p>And then I could access the output values with:</p>
  
  <pre><code>setOutputPin( LINE_0, newState[0] );
  setOutputPin( LINE_1, newState[1] );
  setOutputPin( LINE_2, newState[2] );
  setOutputPin( LINE_3, newState[3] );
  </code></pre>
  
  <p>But in order to get that, it looks like I would have to do a fairly confusing table like so: </p>
  
  <pre><code>static u8 decisionTable[][][][][] =
   {{{{ 0, 0, 0, 0 },
      { 0, 0, 0, 0 }},
     {{ 0, 0, 0, 0 },
      { 0, 0, 0, 0 }}},
    {{{ 0, 0, 1, 1 },
      { 0, 1, 1, 1 }},
     {{ 0, 1, 0, 1 },
      { 1, 1, 1, 1 }}}},
   {{{{ 0, 1, 0, 1 },
      { 1, 1, 1, 1 }},
     {{ 0, 1, 0, 1 },
      { 1, 1, 1, 1 }}},
    {{{ 0, 1, 1, 1 },
      { 0, 1, 1, 1 }},
     {{ 0, 1, 0, 1 },
      { 1, 1, 1, 1 }}}};
  </code></pre>
  
  <p>Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?</p>
  
  <p>Thanks!</p>
  
  <p><strong>Edit based on HUAGHAGUAH's answer:</strong></p>
  
  <p>Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:</p>
  
  <pre><code>#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 &lt;&lt; 0) | (in1 &lt;&lt; 1) | (in2 &lt;&lt; 2) | (in3 &lt;&lt; 3))
  </code></pre>
  
  <p>And that will let my truth table array look like this:</p>
  
  <pre><code>static u8 decisionTable[][] = {
  { 0, 0, 0, 0 },
  { 0, 0, 0, 0 },
  { 0, 0, 0, 0 },
  { 0, 0, 0, 0 },
  { 0, 0, 1, 1 },
  { 0, 1, 1, 1 },
  { 0, 1, 0, 1 },
  { 1, 1, 1, 1 },
  { 0, 1, 0, 1 },
  { 1, 1, 1, 1 },
  { 0, 1, 0, 1 },
  { 1, 1, 1, 1 },
  { 0, 1, 1, 1 },
  { 0, 1, 1, 1 },
  { 0, 1, 0, 1 },
  { 1, 1, 1, 1 }};
  </code></pre>
  
  <p>And I can then access my truth table like so:</p>
  
  <pre><code>decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]
  </code></pre>
  
  <p>I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!</p>