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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值