From a34abc1d1c9fbd565fe00e14372fe815d25ef388 Mon Sep 17 00:00:00 2001 From: ame Date: Mon, 25 Dec 2023 15:10:09 -0600 Subject: arbitrary base convertions --- src/encode/baseN.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/encode/baseN.h | 3 +++ 2 files changed, 56 insertions(+) create mode 100644 src/encode/baseN.c create mode 100644 src/encode/baseN.h (limited to 'src/encode') diff --git a/src/encode/baseN.c b/src/encode/baseN.c new file mode 100644 index 0000000..9c911c2 --- /dev/null +++ b/src/encode/baseN.c @@ -0,0 +1,53 @@ +/* +local function to_base10(inp,basein) + local out = 0 + for i=1,#inp do + out = out + (inp[i]*(basein^(#inp - i))) + end + return out +end + +local function from_base10(inp,outbase) + local out = {} + while inp > 0 do + local rem = inp % outbase + inp = math.floor(inp / outbase) + table.insert(out,1,rem) + end + return out +end +local function baseT_to_N(inp,basein,baseout) + return from_base10(to_base10(inp,basein),baseout) +end +*/ +#include +#include +#include "../lua.h" +#include "../table.h" + +int l_baseconvert(lua_State* L){ + luaL_checktype(L, 1, LUA_TTABLE); + int64_t base_import = luaL_checkinteger(L, 2); + int64_t base_export = luaL_checkinteger(L, 3); + size_t len = lua_objlen(L,1); + uint64_t out = 0; + + for(size_t i = 1; i <= len; i++){ + lua_pushnumber(L, i); + lua_gettable(L, 1); + + out += luaL_checkinteger(L, -1) * pow(base_import, len - i); + } + + lua_newtable(L); + for(int i = 1; out > 0; i++){ + uint64_t rem = out % base_export; + out /= base_export; + + lua_pushnumber(L,i); + lua_pushnumber(L, rem); + lua_settable(L, -3); + } + + return 1; +}; diff --git a/src/encode/baseN.h b/src/encode/baseN.h new file mode 100644 index 0000000..dc4d875 --- /dev/null +++ b/src/encode/baseN.h @@ -0,0 +1,3 @@ +#include "../lua.h" + +int l_baseconvert(lua_State*); -- cgit v1.2.3