Hi,
I have a working C hash function that I turned into a Lua module:
int16_t crc_1021_c(int16_t old_crc, int8_t data)
{
int16_t crc;
int16_t x;
x = ((old_crc>>8) ^ data) & 0xff;
x ^= x>>4;
crc = (old_crc << 8) ^ (x << 12) ^ (x << 5) ^ x;
crc &= 0xffff; //disable this on 16 bit processors
return crc;
}
I run it in a script like this:
local sf = require 'libsf'
print('Lua Calling C hash:')
local crc = 0xffff
local data = "" 0x00, 0x00, 0x0d, 0x00}
for i = 1, 8,1 do
--~ print(data[i])
crc = sf.crc1021(crc, data[i])
end
I happened to be looking at the Lua 5.3 Bitwise Operators reference and the C code looked like I could convert it to Lua, but I get a different number when running the same data through the different codes. My attempted Lua conversion of the C hash:
function ccitt_16_c(byte_array)
local function hash(orig_crc, byte)
local crc
local x;
x = ((orig_crc >> 8) ~ byte) & 0xff;
x = x ~ (x >> 4);
crc = (orig_crc << 8) ~ (x << 12) ~ (x << 5) ~ x;
crc = crc & 0xffff;
return crc
end
local crc = 0xffff
for i in ipairs(byte_array) do
crc = hash(crc, byte_array[i])
end
return crc & 0xffff
end
I get a much different number from the two code bases even though they are run on the same table. Here is my test script:
test-crc.lua:
local sf = require 'libsf'
local lcrc = require 'crc1021'
print('Lua Calling C hash:')
local crc = 0xffff
local data = "" 0x00, 0x00, 0x0d, 0x00}
for i = 1, 8,1 do
--~ print(data[i])
crc = sf.crc1021(crc, data[i])
end
print(crc)
local pl = string.pack('<I<I',0x000a0000,0x000d0000)
print('C on packed string')
local crc = sf.crc16(pl)
print(crc)
print('Lua Clark Li:')
print('Disabled, my variant didn\'t work')
--~ print(lcrc.ccitt_16_l(data))
print('Lua converted C:')
print(lcrc.ccitt_16_c(data))
Results:
C:\Users\russh\projects\NLuaSerialScripts> lua .\test-crc.lua
Lua Calling C hash:
-16032.0
C on packed string
-16032.0
Lua Clark Li:
Disabled, my variant didn't work
Lua converted C:
49504
Any ideas why I get a different number? All input greatly appreciated.
Russ