January 06th 2012

Telit GM862-GPS hex() bug

Tags: code news python embedded Written by Dave Barker

My SHA1 code was returning a different hex digest when run on my Telit GM862 GPS. I eventually tracked the problem down to the hex() function. Simply put hex(3181490320L) does not return the right result!

Run this test script and post your results below.

import sys, SER, MDM

# Set up printing to serial
SER.set_speed('115200', '8N1')
class SerWriter:
  def write(self, s):
    SER.send(s + "\r")
sys.stdout = sys.stderr = SerWriter()

# Simplistic AT command function
def at_command(command):
  # Clear the command interface buffer
  MDM.read()
  # Send the command
  MDM.send(command + '\r', 0)
  # Create a buffer
  buffer = ''
  while 1:
    # Listen to serial port for click
    incoming = MDM.receive(1)
    # If we got some data handle it
    if incoming:
      buffer = buffer + incoming
      if buffer.find("OK") > -1:
        return buffer
      elif buffer.find("ERROR") > -1:
        return ''

# Run the tests
print at_command("AT+CGMM")
print at_command("AT+CGMR")
i = 3181490320L
print i
print long(hex(i), 16)

# Restore standard out
sys.stdout = sys.stderr = sys.__stdout__

My output was:

OK

GM862-GPS

OK


07.03.402

OK

3181490320
2376183952

Cheers, Dave.

Edit: In case anyone’s interested here’s my hex() replacement. It’s probably much slower but it works and can pad the hex string to x bytes.

def write_hex(x, bytes=1):
  h = ['0'] * bytes * 2
  i = 0
  while x > 0:
    if i < bytes * 2:
      h[i] = '0123456789abcdef'[x & 0xf]
    else:
      h.append('0123456789abcdef'[x & 0xf])
    x = x >> 4
    i = i + 1
  h.reverse()
  return ''.join(h)