title: Python parsing serial hex string with fixed format
body: <p>I am successfully communicating with a simple device over serial, with a specific request packet, and a fixed format return packet is received. Im starting with python so I can use this on multiple devices, I'm only really used to PHP/C. </p>
  
  <p>For example, I send the following as hex:</p>
  
  <pre><code>12 05 0b 03 1f
  </code></pre>
  
  <p>and in return I get</p>
  
  <pre><code>12 05 0b 03 1f 12 1D A0 03 18 00 22 00 00 CA D4 4F 00 00 22 D6 99 18 00 70 80 00 80 00 06 06 00 00 D9
  </code></pre>
  
  <p>I know how the packet is constructed, the first 5 bytes is the data that was sent. The next 3 bytes are an ID, the packet length, and a response code. Its commented in my code here:</p>
  
  <pre><code>import serial, time
  
  ser = serial.Serial(port='COM1', baudrate=9600, timeout=0, parity=serial.PARITY_EVEN,      stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
  
  while True:
      # Send The Request - 0x12 0x05 0x0B 0x03 0x1F
      ser.write("\x12\x05\x0B\x03\x1F")
      # Clear first 5 bytes (Original Request is Returned)    
      ser.read(5)
  
      # Response Header (3 bytes)
      # - ID (Always 12)
      # - Packet Length (inc these three)
      # - General Response (a0 = Success, a1 = Busy, ff = Bad Command)
      ResponseHeader = ser.read(3).encode('hex')
      PacketLength = int(ResponseHeader[2:4],16)
      if ResponseHeader[4:6] == "a0":
          # Response Success
          ResponseData = ser.read(PacketLength).encode('hex')
          # Read First Two Bytes        
          Data1 = int(ResponseData[0:4],16)
          print Data1
      else:
          # Clear The Buffer
          RemainingBuffer = ser.inWaiting()
          ser.read(RemainingBuffer)
  
  time.sleep(0.12)
  </code></pre>
  
  <p>To keep it simple for now, I was just trying to read the first two bytes of the actual response (ResponseData), which should give me the hex 0318. I then want to output that as a decimal =792. The program is meant to run in a continuous loop.</p>
  
  <p>Some of the variables in the packet are one byte, some are two bytes. Although, up to now I'm just getting an error:</p>
  
  <pre><code>ValueError: invalid literal for int() with base 16: ''
  </code></pre>
  
  <p>I'm guessing this is due to the format of the data/variables I have set, so not sure if I'm even going about this the right way. I just want to read the returned HEX data in byte form and be able to access them on an individual level, so I can format/output them as required.</p>
  
  <p>Is there a better way to do this? Many thanks.</p>