aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorame <[email protected]>2023-12-25 15:10:09 -0600
committerame <[email protected]>2023-12-25 15:10:09 -0600
commita34abc1d1c9fbd565fe00e14372fe815d25ef388 (patch)
treec9cee3eafcf00053952e7965bf47feaf828dfd30
parent80450829684b075d0324aea16df7bbfaed0034c4 (diff)
arbitrary base convertions
-rw-r--r--docs/crypto.md11
-rw-r--r--src/crypto.h2
-rw-r--r--src/encode/baseN.c53
-rw-r--r--src/encode/baseN.h3
4 files changed, 69 insertions, 0 deletions
diff --git a/docs/crypto.md b/docs/crypto.md
index 01fe7be..997ede9 100644
--- a/docs/crypto.md
+++ b/docs/crypto.md
@@ -77,3 +77,14 @@ all functions have 1 argument which is a string, unless noted otherwise
llib.crypto.base64encode("purr") -- cHVycg==
llib.crypto.base64decode("cHVycg==") -- purr
```
+
+## baseconvert
+
+'accepts an array of integers
+
+converts an array from base N to base T (in reversed order)
+
+```lua
+-- input N T
+llib.crypto.baseconvert({1, 1, 0, 1, 0, 1, 0, 0, 0, 1}, 2, 10) -- {9, 4, 8} (which is 849)
+```
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*);