crc_xmodem.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #import cProfile
  33. #cProfile.run('test_performance()')
  34. if sys.argv[1].endswith(".smc"):
  35. copy_header= True
  36. size = os.stat(sys.argv[1])[6]
  37. fd = open(sys.argv[1])
  38. if copy_header:
  39. fd.seek(512)
  40. size = size - 512
  41. addr = 0x0000
  42. step = 2**15
  43. result = []
  44. while addr < size:
  45. try:
  46. block = fd.read(step)
  47. addr += step
  48. except:
  49. print "Done"
  50. break
  51. crc = do_crc(block)
  52. print "Bank: 0x%02x Addr: 0x%06x Block: 0x%04x CRC 0x%04x" % (addr/(2**15),addr,addr/512, ctypes.c_uint16(crc).value)
  53. result.append(hex(ctypes.c_uint16(crc).value))
  54. #print result
  55. if __name__ == '__main__':
  56. #test_algo()
  57. main()