title: Lua: Hexadecimal Word to Binary Conversion
body: <p>I'm attempting to create a Lua program to monitor periodic status pings of a slave device.  The slave device sends its status in 16-bit hexadecimal words, which I need to convert to a binary string since each bit pertains to a property of the device.  I can receive the input string, and I have a table containing 16 keys for each parameter.  But I am having a difficult time understanding how to convert the hexadecimal word into a string of 16-bits so I can monitor it.</p>
  
  <p>Here is a basic function of what I'm starting to work on.</p>
  
  <pre><code>function slave_Status(IP,Port,Name)
      status = path:read(IP,Port)
      sTable = {}
      if status then
          sTable.ready=bit32.rshift(status:byte(1), 0)
          sTable.paused=bit32.rshift(status:byte(1), 1)
          sTable.emergency=bit32.rshift(status:byte(1), 2)
          sTable.started=bit32.rshift(status:byte(1), 3)
          sTable.busy=bit32.rshift(status:byte(1), 4)
          sTable.reserved1=bit32.rshift(status:byte(1), 5)
          sTable.reserved2=bit32.rshift(status:byte(1), 6)
          sTable.reserved3=bit32.rshift(status:byte(1), 7)
          sTable.reserved4=bit32.rshift(status:byte(2), 0)
          sTable.delay1=bit32.rshift(status:byte(2), 1)
          sTable.delay2=bit32.rshift(status:byte(2), 2)
          sTable.armoff=bit32.rshift(status:byte(2), 3)
          sTable.shieldoff=bit32.rshift(status:byte(2), 4)
          sTable.diskerror=bit32.rshift(status:byte(2), 5)
          sTable.conoff=bit32.rshift(status:byte(2), 6)
          sTable.envoff=bit32.rshift(status:byte(2), 7)
      end
  end
  </code></pre>
  
  <p>I hope this approach is understandable?  I'd like to receive the Hex strings, for example <code>0x18C2</code> and turn that to <code>0001 1000 1100 0010</code>, shifting the right-most bit to the right and placing that into the proper key.  Then later in the function I would monitor if that bit had changed for the better or worse.   </p>
  
  <p>If I run a similar function in Terminator in Linux, and print out the pairs I get the following return:</p>
  
  <pre><code>49
  24
  12
  6
  3
  1
  0
  0
  56
  28
  14
  7
  3
  1
  0
  0
  </code></pre>
  
  <p>This is where I am not understanding how to take each value and set it to bits</p>
  
  <p>I'm pretty new to this so I do not doubt that there is an easier way to do this.  If I need to explain further I will try.</p>