Logic Machine Forum
Lua CRC16-ccitt example - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Scripting (https://forum.logicmachine.net/forumdisplay.php?fid=8)
+--- Thread: Lua CRC16-ccitt example (/showthread.php?tid=4127)



Lua CRC16-ccitt example - AEK - 01.07.2022

Hi, just sharing
Code:
data = ('njhyTFGV')
init = 0xffff
crc = init
function crc16_ccitt(crc, data)
  msb = bit.rshift(crc , 8)
  lsb = bit.band(crc , 255)
  --log(msb, lsb)
  for i = 1, #data do
    strb = string.byte(data, i, i)
    x = bit.bxor(strb, msb)
    --log(strb,msb, x)
    x = bit.bxor(x,  bit.rshift(x,4))
    --log(x)
    msb = bit.band(bit.bxor(lsb , bit.rshift(x , 3) , bit.lshift(x , 4)) , 255)
    lsb = bit.band(bit.bxor(x , bit.lshift(x , 5)) , 255)
    log(msb, lsb, x)
    end
  res = lsb + bit.lshift(msb, 8)
  return res , string.format('%x', res)
end
 
log(crc16_ccitt(crc, data))
results was tested with this service
https://crccalc.com/

original code was made on Python, was taken here in comments
https://stackoverflow.com/questions/25239423/crc-ccitt-16-bit-python-manual-calculation