about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--base64.c29
1 files changed, 28 insertions, 1 deletions
diff --git a/base64.c b/base64.c
index e649728..acc9999 100644
--- a/base64.c
+++ b/base64.c
@@ -32,6 +32,7 @@
 
 #include <unistd.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 
@@ -54,7 +55,33 @@ static void usage(const char *name) {
 }
 
 char *base64(char *i, ssize_t length, unsigned dflg){
-    return i;
+    if (dflg) return NULL;
+    char *out = malloc(length/3 * 4 + 100);
+    char *start_p = out;
+    while (length > 0) {
+        char i1, i2;
+        i1 = i2 = 0;
+        length -= 3;
+        if (length >= -2) {
+            i2 = i[2];
+            if (length >= -1) i1 = i[1];
+        }
+        *out = tbl_base64[i[0] >> 2];
+        ++out;
+        *out = tbl_base64[((i[0] & 3) << 4) + (i1 >> 2)];
+        ++out;
+        *out = tbl_base64[((i1 & 3) << 4) + (i2 >> 2)];
+        ++out;
+        *out = tbl_base64[i2 & 0x3f];
+        ++out;
+        i += 3;
+    }
+    *out = '\0';
+    while (length < 0){
+        length++;
+        *--out = tbl_base64[64];
+    }
+    return start_p;
 }
 
 int main(int argc, char **argv) {