|
1 local bit = require "bit"; |
|
2 |
|
3 module "crc16" |
|
4 |
|
5 function hash(str) |
|
6 local crc; |
|
7 |
|
8 local function initCrc() |
|
9 crc = 0xffff; |
|
10 end |
|
11 |
|
12 local function updCrc(byte) |
|
13 crc = bit.bxor(crc, byte); |
|
14 for i=1,8 do |
|
15 local j = bit.band(crc, 1); |
|
16 crc = bit.rshift(crc, 1); |
|
17 if j ~= 0 then |
|
18 crc = bit.bxor(crc, 0x8408); |
|
19 end |
|
20 end |
|
21 end |
|
22 |
|
23 local function getCrc(str) |
|
24 initCrc(); |
|
25 for i = 1, #str do |
|
26 updCrc(str:byte(i)); |
|
27 end |
|
28 return crc; |
|
29 end |
|
30 return getCrc(str); |
|
31 end |
|
32 |
|
33 return { hash = hash } |