crc16.rb 501 B

12345678910111213141516171819202122232425
  1. CRC_POLY = 0x8408
  2. def calc_crc(data, poly = CRC_POLY)
  3. state = 0;
  4. data.each do |byte|
  5. 8.times do
  6. if ((byte ^ state) & 0x01) == 0x01
  7. state = (state >> 1) ^ poly;
  8. #printf "^ "
  9. else
  10. state = state >> 1;
  11. #printf "> "
  12. end
  13. #printf "%08b %016b // %02X %04X \n", byte, state, byte, state
  14. byte = byte >> 1;
  15. end
  16. #printf "---\n"
  17. end
  18. state
  19. end
  20. input = gets.strip
  21. r = calc_crc([input].pack('H*').bytes)
  22. printf "%04X (%d)\n", r, r