个人开发的,主要供软件开发者进行base64码校对使用。
界面如下:
生成base64的函数代码如下:
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int Base64Enc(const char *src, int len, char *r) { unsigned char* q=(unsigned char*)src; char *p = r; for(; len >= 3; len -= 3, q += 3) { *p++ = base64[q[0] >> 2]; *p++ = base64[((q[0] & 0x3) << 4) | (q[1] >> 4)]; *p++ = base64[((q[1] & 0xF) << 2) | (q[2] >> 6)]; *p++ = base64[q[2] & 0x3F]; } if(len > 0) { *p++ = base64[q[0] >> 2]; if(len == 1 ) { *p++ = base64[(q[0] & 0x3) << 4]; *p++ = '='; } else // len == 2 { *p++ = base64[((q[0] & 0x3) << 4) | (q[1] >> 4)]; *p++ = base64[(q[1] & 0xF) << 2]; } *p++ = '='; } return p - r; }
base64解码的源代码函数如下:
static int get6bits(char c) { if(c >= 'A' && c <= 'Z') return c - 'A'; if(c >= 'a' && c <= 'z') return c - 'a' + 26; if(c >= '0' && c <= '9') return c - '0' + 52; if(c == '+') return 62; if(c == '/') return 63; return -1; } int Base64Dec(const char *src, int len, char *r) { char *p = r; int i, bits, code; int k = 0; // 指示当前code中的bit数 for(i=0; i<len; i++) { bits = get6bits(src[i]); if(bits < 0) break; if(k == 0) { code = (bits << 2); k = 6; } else if(k == 6) { code |= (bits >> 4); *p++ = code; k = 4; code = (bits << 4); } else if(k == 4) { code |= (bits >> 2); *p++ = code; k = 2; code = (bits << 6); } else if(k == 2) { code |= bits; *p++ = code; k = 0; } } return p - r; }