stm32_crc.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright 2024 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. CRC_POLY = 0x04C11DB7
  15. def precompute_table(bits):
  16. lookup_table = []
  17. for i in range(2**bits):
  18. rr = i << (32 - bits)
  19. for x in range(bits):
  20. if rr & 0x80000000:
  21. rr = (rr << 1) ^ CRC_POLY
  22. else:
  23. rr <<= 1
  24. lookup_table.append(rr & 0xffffffff)
  25. return lookup_table
  26. lookup_table = precompute_table(8)
  27. def process_word(data, crc=0xffffffff):
  28. if (len(data) < 4):
  29. # The CRC data is "padded" in a very unique and confusing fashion.
  30. data = data[::-1] + b'\0' * (4 - len(data))
  31. for char in reversed(data):
  32. b = char
  33. crc = ((crc << 8) ^ lookup_table[(crc >> 24) ^ b]) & 0xffffffff
  34. return crc
  35. def process_buffer(buf, c=0xffffffff):
  36. word_count = (len(buf) + 3) // 4
  37. crc = c
  38. for i in range(word_count):
  39. crc = process_word(buf[i * 4 : (i + 1) * 4], crc)
  40. return crc
  41. def crc32(data):
  42. return process_buffer(data)
  43. if __name__ == '__main__':
  44. import sys
  45. assert(0x89f3bab2 == process_buffer("123 567 901 34"))
  46. assert(0xaff19057 == process_buffer("123456789"))
  47. assert(0x519b130 == process_buffer("\xfe\xff\xfe\xff"))
  48. assert(0x495e02ca == process_buffer("\xfe\xff\xfe\xff\x88"))
  49. print("All tests passed!")
  50. if len(sys.argv) >= 2:
  51. b = open(sys.argv[1]).read()
  52. crc = crc32(b)
  53. print("%u or 0x%x" % (crc, crc))