2 Коммиты 882765075d ... 3ce99ca097

Автор SHA1 Сообщение Дата
  David Ulrich 3ce99ca097 Merge branch 'master' of notabug.org:yzziizzy/sti 1 год назад
  David Ulrich ba29a5f706 initial pass at base64_encode 1 год назад
4 измененных файлов с 79 добавлено и 8 удалено
  1. 54 0
      b64.c
  2. 1 1
      b64.h
  3. 24 7
      test/b64.c
  4. BIN
      test/b64test

+ 54 - 0
b64.c

@@ -89,6 +89,60 @@ void base64_decode(char* in, uint64_t inLen, uint8_t* out, uint64_t* outLen) {
 }
 
 
+static inline char charfromhextet(uint8_t h) {
+	if(h < 26) return h + 'A';
+	if(h < 52) return h - 26 + 'a';
+	if(h < 62) return h - 52 + '0';
+	if(h == 62) return '+';
+	if(h == 63) return '/';
+	return 0;
+}
+
+
+void base64_encode(char* in, uint64_t inLen, char* out, uint64_t* outLen) {
+	
+	uint64_t trios = inLen / 3;
+	uint64_t rem = inLen % 3;
+	
+	uint64_t o = 0;
+	
+	uint64_t i = 0;
+	for(uint64_t j = 0; j < trios; j++, i += 3) {
+		uint32_t x = 0;
+		
+		x = (in[i + 0] << 16 | in[i + 1] << 8 | in[i + 2]);
+		
+		out[o + 0] = charfromhextet((x >> 18) & 0b00111111);
+		out[o + 1] = charfromhextet((x >> 12) & 0b00111111);
+		out[o + 2] = charfromhextet((x >> 6) & 0b00111111);
+		out[o + 3] = charfromhextet((x >> 0) & 0b00111111);
+		
+		o += 4;
+	}
+	
+	*outLen = trios * 4;
+	
+	if(!rem) return;
+	(*outLen) += 4;
+	
+	out[o + 3] = '=';
+	
+	uint32_t x = 0;
+	x = (in[i + 0] << 16);
+	
+	if(rem == 2) {
+		x |= (in[i + 1] << 8);
+		out[o + 2] = charfromhextet((x >> 6) & 0b00111111);
+	}
+	else {
+		out[o + 2] = '=';
+	}
+	
+	out[o + 0] = charfromhextet((x >> 18) & 0b00111111);
+	out[o + 1] = charfromhextet((x >> 12) & 0b00111111);
+	
+}
+
 
 
 

+ 1 - 1
b64.h

@@ -6,7 +6,7 @@
 
 
 void base64_decode(char* in, uint64_t inLen, uint8_t* out, uint64_t* outLen);
-
+void base64_encode(char* in, uint64_t inLen, char* out, uint64_t* outLen);
 
 
 

+ 24 - 7
test/b64.c

@@ -8,7 +8,7 @@
 
 #define ERROR(a, ...) printf("%s:%d  " a "\n", __FILE__, __LINE__ __VA_OPT__(,) __VA_ARGS__)
 
-void b64t(char* test) {
+void b64t_decode(char* test) {
 	uint8_t buf[10000];
 	uint64_t outlen = 0;
 	
@@ -22,17 +22,34 @@ void b64t(char* test) {
 }
 
 
+void b64t_encode(char* test) {
+	char buf[10000];
+	uint64_t outlen = 0;
+	
+	base64_encode(test, strlen(test), buf, &outlen);
+	
+	for(uint64_t i = 0; i < outlen; i++) {
+		printf("%c", buf[i]);
+	}
+	
+	printf("\n");
+}
+
 
 int main(/*int argc, char* argv[]*/) {
 
-	b64t("bGlnaHQgdw");
-	b64t("bGlnaHQgd28");
-	b64t("bGlnaHQgd29y");
+	b64t_decode("bGlnaHQgdw");
+	b64t_decode("bGlnaHQgd28");
+	b64t_decode("bGlnaHQgd29y");
 	
-	b64t("bGlnaHQgdw==");
-	b64t("bGlnaHQgd28=");
-	b64t("TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu");
+	b64t_decode("bGlnaHQgdw==");
+	b64t_decode("bGlnaHQgd28=");
+	b64t_decode("TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu");
 	
+	b64t_encode("light w");
+	b64t_encode("light wo");
+	b64t_encode"light wor");
+	b64t_encode("Many hands make light work.");
 	
 	return 0;
 }