21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

If the length of the input string isn’t a multiple of three bytes, the leftover bits are<br />

padded to a multiple of six with zeros; then the last character is encoded. If only one<br />

byte would have been needed in the input to make it a multiple of three, the pad<br />

character (=) is added to the end of the string. Otherwise, two pad characters are<br />

added.<br />

#include <br />

static char b64table[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"<br />

"abcdefghijklmnopqrstuvwxyz"<br />

"0123456789+/";<br />

/* Accepts a binary buffer with an associated size.<br />

* Returns a base64 encoded, NULL-terminated string.<br />

*/<br />

unsigned char *spc_base64_encode(unsigned char *input, size_t len, int wrap) {<br />

unsigned char *output, *p;<br />

size_t i = 0, mod = len % 3, toalloc;<br />

toalloc = (len / 3) * 4 + (3 - mod) % 3 + 1;<br />

if (wrap) {<br />

toalloc += len / 57;<br />

if (len % 57) toalloc++;<br />

}<br />

p = output = (unsigned char *)malloc(((len / 3) + (mod ? 1 : 0)) * 4 + 1);<br />

if (!p) return 0;<br />

while (i < len - mod) {<br />

*p++ = b64table[input[i++] >> 2];<br />

*p++ = b64table[((input[i - 1] > 4)) & 0x3f];<br />

*p++ = b64table[((input[i] > 6)) & 0x3f];<br />

*p++ = b64table[input[i + 1] & 0x3f];<br />

i += 2;<br />

if (wrap && !(i % 57)) *p++ = '\n';<br />

}<br />

if (!mod) {<br />

if (wrap && i % 57) *p++ = '\n';<br />

*p = 0;<br />

return output;<br />

} else {<br />

*p++ = b64table[input[i++] >> 2];<br />

*p++ = b64table[((input[i - 1] > 4)) & 0x3f];<br />

if (mod = = 1) {<br />

*p++ = '=';<br />

*p++ = '=';<br />

if (wrap) *p++ = '\n';<br />

*p = 0;<br />

return output;<br />

} else {<br />

*p++ = b64table[(input[i]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!