2

I need convert this C function to a Lua function

I'm porting a simple project to LuaJIT, my port is 99% done, but this function has some problem. What am I missing?

/**
*  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;
}

At moment, my current Lua function is this:

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

Thanks in advance

4

1 回答 1

3

您忘记调用string.char已处理的字节:

result = result .. string.char(bit.bxor(string.byte(arg1, index), string.byte(arg2, index)))

还有一些提示:

  1. 使用 for 循环,会更快。
  2. bit.bxor对,string.byte和使用外部本地变量string.char
  3. 通用名称是 xor,而不是 ex_or(它不是或不再是......;-))。
于 2014-04-17T23:33:54.263 回答