diff options
| author | ame <[email protected]> | 2023-12-25 15:10:09 -0600 |
|---|---|---|
| committer | ame <[email protected]> | 2023-12-25 15:10:09 -0600 |
| commit | a34abc1d1c9fbd565fe00e14372fe815d25ef388 (patch) | |
| tree | c9cee3eafcf00053952e7965bf47feaf828dfd30 /src | |
| parent | 80450829684b075d0324aea16df7bbfaed0034c4 (diff) | |
arbitrary base convertions
Diffstat (limited to 'src')
| -rw-r--r-- | src/crypto.h | 2 | ||||
| -rw-r--r-- | src/encode/baseN.c | 53 | ||||
| -rw-r--r-- | src/encode/baseN.h | 3 |
3 files changed, 58 insertions, 0 deletions
diff --git a/src/crypto.h b/src/crypto.h index fc1101e..564ea58 100644 --- a/src/crypto.h +++ b/src/crypto.h @@ -28,6 +28,7 @@ #include "encode/uuencode.h" #include "encode/base64.h" +#include "encode/baseN.h" unsigned i_lr(unsigned, unsigned); unsigned i_rr(unsigned, unsigned); @@ -63,6 +64,7 @@ static const luaL_Reg crypto_function_list [] = { {"base64encode",l_base64encode}, {"base64decode",l_base64decode}, + {"baseconvert",l_baseconvert}, {NULL,NULL} }; 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 <math.h> +#include <stdint.h> +#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*); |
