Commits

carl douglas committed 531c288

driving round in my tractor

Comments (0)

Files changed (1)

 #/* 
-# * 
 # * Base64 decoder
+# * Copyright (c) 2011 A. Carl Douglas
 # *
-# * To compile as a standalone program:
+# * To compile the test program:
 # *   make -f b64.c
-# *
 # */
 
 # /* Makefile
 
 b64: b64.c
-	gcc -Wall -ansi -o b64 b64.c -DALONE
+	gcc -Wall -ansi -o b64 b64.c -DBASE64_TEST
 
 clean:
 	rm b64
 
 #include <stdio.h>
 #include <string.h>
-#include <ctype.h>
 
-/* subtract 40 from base64 ASCII value to get index in this table */
+/* subtract 40 from base64 ASCII representation to get index in this table */
 static unsigned char decode_tab[] = {
   -1, -1, -1, 62, -1, -1, -1, 63, 
   52, 53, 54, 55, 56, 57, 58, 59, 
 
 /*
  * dst should be 3/4 the size of src
- *
  */
 void 
 base64_decode(char *src, char *dst) {
-  unsigned char           *ptr;
-  unsigned char           *out;
-  out = (unsigned char *)dst;
-  ptr = (unsigned char *)src;
-  for (; *ptr; ) {
+  unsigned char           *ptr = (unsigned char *)src;
+  unsigned char           *out = (unsigned char *)dst;
+  int i;
+  for (; *ptr && (*ptr != '='); ) {
     unsigned char blk[4] = { 0 };
-    int i;
-    blk[0] = 0; blk[1] = 0; blk[2] = 0; blk[3] = 0;
-    for (i=0; *ptr && (i < 4); i++, ptr++) {
-      int v = (*ptr-40);
-      if (*ptr == '=') break;
-      blk[i] = decode_tab[v];
+    for (i = 0; *ptr && (*ptr != '=') && (i < 4); i++, ptr++) {
+      blk[i] = decode_tab[*ptr-40];
+      switch(i){
+        case 1: *out++ = ((blk[0]&0x3f) << 2) | ((blk[1]&0x30) >> 4); break;
+        case 2: *out++ = ((blk[1]&0x0f) << 4) | ((blk[2]&0x3c) >> 2); break;
+        case 3: *out++ = ((blk[2]&0x03) << 6) | ((blk[3]&0x3f) >> 0); break;
+      }
     }
-    *out++ = ((blk[0]&0x3f) << 2) | ((blk[1]&0x30) >> 4);
-    *out++ = ((blk[1]&0x0f) << 4) | ((blk[2]&0x3c) >> 2);
-    *out++ = ((blk[2]&0x03) << 6) | ((blk[3]&0x3f) >> 0);
-
-    if (*ptr == '=') break;
   }
   *out   = '\0';
 }
 
-#ifdef ALONE
+#ifdef BASE64_TEST
 int main (int argc, char *argv[]) {
 
    char *tst[] = {