crc32.sf 809 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/ruby
  2. # Simple implementation of the Cyclic Redundancy Check (CRC32).
  3. # Reference:
  4. # https://web.archive.org/web/20240718094514/https://rosettacode.org/wiki/CRC-32
  5. func create_crc32_table {
  6. 256.of {|k|
  7. 8.times {
  8. if (k & 1) {
  9. k >>= 1
  10. k ^= 0xedb88320
  11. }
  12. else {
  13. k >>= 1
  14. }
  15. }
  16. k
  17. }
  18. }
  19. func crc32(str, crc = 0) {
  20. static crc_table = create_crc32_table()
  21. crc &= 0xffffffff
  22. crc ^= 0xffffffff
  23. str.codes.each {|c|
  24. crc = ((crc >> 8) ^ crc_table[(crc & 0xff) ^ c])
  25. }
  26. return ((crc & 0xffffffff) ^ 0xffffffff)
  27. }
  28. say crc32("The quick brown fox jumps over the lazy dog").as_hex
  29. say crc32("over the lazy dog", crc32("The quick brown fox jumps ")).as_hex