crc_xmodem.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import ctypes
  2. import sys
  3. import os
  4. def crc_xmodem_update(crc, data):
  5. crc = ctypes.c_uint16(crc.value ^ data.value << 8)
  6. for i in range(0, 8):
  7. if crc.value & 0x8000:
  8. crc = ctypes.c_uint16((crc.value << 1) ^ 0x1021)
  9. else:
  10. crc = ctypes.c_uint16(crc.value << 1)
  11. return crc
  12. def do_crc(data):
  13. crc = ctypes.c_uint16(0)
  14. for idx, char in enumerate(data):
  15. crc = crc_xmodem_update(crc, ctypes.c_uint8(ord(char)))
  16. return crc.value
  17. def test_performance():
  18. data = str()
  19. fd = open("/dev/urandom")
  20. for i in range(0, 256):
  21. data += fd.read(1024)
  22. sys.stdout.write("*")
  23. sys.stdout.flush()
  24. print
  25. fd.close()
  26. print "%s" % do_crc(data)
  27. def test_algo():
  28. data = 'david'
  29. data = 'da'
  30. print "%x" % do_crc(data)
  31. def main():
  32. if sys.argv[1].endswith(".smc"):
  33. copy_header = True
  34. size = os.stat(sys.argv[1])[6]
  35. fd = open(sys.argv[1])
  36. if copy_header:
  37. fd.seek(512)
  38. size = size - 512
  39. addr = 0x0000
  40. step = 2 ** 15
  41. result = []
  42. while addr < size:
  43. try:
  44. block = fd.read(step)
  45. addr += step
  46. except:
  47. print "Done"
  48. break
  49. crc = do_crc(block)
  50. print "Bank: 0x%02x Addr: 0x%06x Block: 0x%04x CRC 0x%04x" % (addr / (2 ** 15), addr, addr / 512, ctypes.c_uint16(crc).value)
  51. result.append(hex(ctypes.c_uint16(crc).value))
  52. # print result
  53. if __name__ == '__main__':
  54. # test_algo()
  55. main()