Back to index

avfs  1.0.1
Functions | Variables
base64.c File Reference
#include "ne_alloc.h"
#include "base64.h"

Go to the source code of this file.

Functions

char * base64 (const char *text)

Variables

static const char b64_alphabet [65]

Function Documentation

char* base64 ( const char *  text)

Definition at line 43 of file base64.c.

{
    /* The tricky thing about this is doing the padding at the end,
     * doing the bit manipulation requires a bit of concentration only */
    char *buffer, *point;
    int inlen, outlen;
    
    /* Use 'buffer' to store the output. Work out how big it should be...
     * This must be a multiple of 4 bytes */

    inlen = strlen(text);
    outlen = (inlen*4)/3;
    if ((inlen % 3) > 0) /* got to pad */
       outlen += 4 - (inlen % 3);
    
    buffer = ne_malloc(outlen + 1); /* +1 for the \0 */
    
    /* now do the main stage of conversion, 3 bytes at a time,
     * leave the trailing bytes (if there are any) for later */

    for (point=buffer; inlen>=3; inlen-=3, text+=3) {
       *(point++) = b64_alphabet[ (*text)>>2 ]; 
       *(point++) = b64_alphabet[ ((*text)<<4 & 0x30) | (*(text+1))>>4 ]; 
       *(point++) = b64_alphabet[ ((*(text+1))<<2 & 0x3c) | (*(text+2))>>6 ];
       *(point++) = b64_alphabet[ (*(text+2)) & 0x3f ];
    }

    /* Now deal with the trailing bytes */
    if (inlen > 0) {
       /* We always have one trailing byte */
       *(point++) = b64_alphabet[ (*text)>>2 ];
       *(point++) = b64_alphabet[ (((*text)<<4 & 0x30) |
                                 (inlen==2?(*(text+1))>>4:0)) ]; 
       *(point++) = (inlen==1?'=':b64_alphabet[ (*(text+1))<<2 & 0x3c ]);
       *(point++) = '=';
    }

    /* Null-terminate */
    *point = '\0';

    return buffer;
}

Variable Documentation

const char b64_alphabet[65] [static]
Initial value:
 { 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/=" }

Definition at line 38 of file base64.c.