libowfat/textcode/fmt_base64.c

25 lines
638 B
C
Raw Normal View History

2002-04-30 13:30:51 +00:00
#include "fmt.h"
#include "textcode.h"
#include "haveinline.h"
2006-11-07 17:56:05 +00:00
size_t fmt_base64(char* dest,const char* src,size_t len) {
2002-04-30 13:30:51 +00:00
register const unsigned char* s=(const unsigned char*) src;
unsigned short bits=0,temp=0;
size_t written=0,i;
if (!dest) return (len>((size_t)-1)/2)?(size_t)-1:((len+2)/3)*4;
2002-04-30 13:30:51 +00:00
for (i=0; i<len; ++i) {
temp<<=8; temp+=s[i]; bits+=8;
while (bits>6) {
2005-04-12 06:48:39 +00:00
dest[written]=base64[((temp>>(bits-6))&63)];
2002-04-30 13:30:51 +00:00
++written; bits-=6;
}
}
if (bits) {
temp<<=(6-bits);
2005-04-12 06:48:39 +00:00
dest[written]=base64[temp&63];
2002-04-30 13:30:51 +00:00
++written;
}
2005-04-12 06:48:39 +00:00
while (written&3) { dest[written]='='; ++written; }
2002-04-30 13:30:51 +00:00
return written;
}