Advertisement
Schneemann

crc32.lua

Sep 15th, 2021
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. local sysnative = not not package.loadlib
  2. local datacard = nil
  3. if not sysnative then
  4. local component = require("component")
  5. if component.isAvailable("data") then
  6. datacard = component.data
  7. end
  8. end
  9.  
  10. -- CRC32 implementation
  11. -- standard table lookup version
  12. local crctab = {}
  13.  
  14. local i
  15. for i=0,256-1 do
  16. local j
  17. local v = i
  18. --[[
  19. v = ((v<<4)|(v>>4)) & 0xFF
  20. v = ((v<<2)&0xCC)|((v>>2)&0x33)
  21. v = ((v<<1)&0xAA)|((v>>1)&0x55)
  22. ]]
  23.  
  24. for j=1,8 do
  25. if (v&1) == 0 then
  26. v = v>>1
  27. else
  28. v = (v>>1) ~ 0xEDB88320
  29. end
  30. end
  31. crctab[i+1] = v
  32. end
  33.  
  34. local crc = {}
  35. function crc.crc32(str, v)
  36. v = v or 0
  37. if v == 0 and datacard ~= nil then
  38. local a = datacard.crc32(str)
  39. v = string.byte(a, 1) | (string.byte(a, 2) << 8) | (string.byte(a, 3) << 16)
  40. v = v | (string.byte(a, 4) << 24)
  41. return v
  42. end
  43. v = v ~ 0xFFFFFFFF
  44.  
  45. local i
  46. for i=1,#str do
  47. --print(str:byte(i))
  48. v = (v >> 8) ~ crctab[((v&0xFF) ~ str:byte(i))+1]
  49. end
  50.  
  51. v = v ~ 0xFFFFFFFF
  52. return v
  53. end
  54.  
  55. return crc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement