我需要将此C
函数转换为Lua
函数
我将一个简单的项目移植到LuaJIT,我的端口完成了99%,但是这个功能有一些问题。我错过了什么?
/**
* X-Or. Does a bit-a-bit exclusive-or of two strings.
* @param s1: arbitrary binary string.
* @param s2: arbitrary binary string with same length as s1.
* @return a binary string with same length as s1 and s2,
* where each bit is the exclusive-or of the corresponding bits in s1-s2.
*/
static int ex_or (lua_State *L) {
size_t l1, l2;
const char *s1 = luaL_checklstring(L, 1, &l1);
const char *s2 = luaL_checklstring(L, 2, &l2);
luaL_Buffer b;
luaL_argcheck( L, l1 == l2, 2, "lengths must be equal" );
luaL_buffinit(L, &b);
while (l1--) luaL_putchar(&b, (*s1++)^(*s2++));
luaL_pushresult(&b);
return 1;
}
目前,我当前的Lua
功能就是:
local bit = require('bit')
function ex_or(arg1, arg2)
if #arg1 == #arg2 then
local result = ""
local index = 1
while index <= #arg1 do
result = result .. bit.bxor(string.byte(arg1, index), string.byte(arg2, index))
index = index + 1
end
return result
else
error("lengths must be equal.")
end
end
提前致谢
答案 0 :(得分:3)
您忘记在已处理的字节上调用string.char
:
result = result .. string.char(bit.bxor(string.byte(arg1, index), string.byte(arg2, index)))
更多提示:
bit.bxor
,string.byte
和string.char
的外部本地人。