Lua--CRC8/MAXIM校验

使用方法:(适用于lua5.3)

1,先创建一个xxx.c文件,写入下面代码

#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

unsigned char crc8(const unsigned char *ptr,unsigned char len)
{
    unsigned char i;
    unsigned char crc = 0;
    while(len--!=0)
    {
        for(i = 1; i != 0; i *= 2){
            if((crc & 1) != 0){
                crc /= 2;
                crc ^= 0x8C;
            }else{
                crc /= 2;
            }
            if((*ptr & i) != 0){
                crc ^= 0x8C;
            }
        }
        ptr++;
    }
    return (crc);
}

int CRC8(lua_State *L)
{
    int i = 0;
    const unsigned char *str = luaL_checkstring(L,1);/*取出LUA调用CRC8函数时传递的第1个参数*/
    int len = luaL_checknumber(L,2);/*取出LUA调用CRC8函数时传递的第2个参数*/
    unsigned char ret = crc8(str,len);
    lua_pushinteger(L,ret);/*CRC8函数在LUA中的返回值*/
    return 1;
}

static luaL_Reg crclibs[] = {
    {"CRC8",CRC8}, /*此处就是提供给LUA调用的函数数组,用于luaL_setfuncs()函数注册*/
    {NULL,NULL}
};

int luaopen_libcrc(lua_State* L)
{
/*步骤2生成的动态库的名称 要和 "luaopen_libcrc" 中 "libcrc" 这几个字符一样,不然会报错*/
    lua_newtable(L);
/*注册数组crclibs 中的所有函数*/
    luaL_setfuncs(L,crclibs,0);
    return 1;
}

2,编译上面代码生成lua使用的动态库

gcc -fPIC -shared xxx.c -o libcrc.so

 

3,测试使用该库

local mylib = require("libcrc")

local cmd = {0x55,0xAA,0x04,0x05}

local str = ""

local len = #cmd  --表cmd的长度

for i=1,len do
    str = str..string.format("%c",cmd[i])
end

local crc = mylib.CRC8(str,len)  --由于未找到lua传递表到C 的函数,所以这里采用传递了字符串

4,lua脚本实现的crc8(需要lua5.3)

function crc8(arr)
	local crc = 0
	local tmp = 0
	local n = 1
	local i = 1
	local len = #arr
	while len ~= 0 do
		i = 1
		repeat
			tmp = crc & 1
			if tmp ~= 0 then
				crc = math.modf(crc/2)
				crc = crc ~ 0x8c
			else 
				crc = math.modf(crc/2)
			end
			tmp = arr[n]
			tmp = tmp & i
			if tmp ~= 0 then
				crc = crc ~ 0x8c
			end
			i = i * 2	
		until(i == 256)
		n = n + 1
		len = len - 1
	end
	return crc
end

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章