首页 > 代码库 > base64解码
base64解码
网络传输经常用base64编码的数据,因此我们需要将其解码成正常字符集合。
base64.h
1 #ifdef __cplusplus 2 extern "C" { 3 #endif 4 5 char * base64_encode( const unsigned char * bindata, char * base64, int binlength ); 6 int base64_decode( const char * base64, unsigned char * bindata ); 7 8 #ifdef __cplusplus 9 }10 #endif
base64.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include "base64.h" 5 6 #ifndef MAX_PATH 7 #define MAX_PATH 256 8 #endif 9 10 const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";11 12 char * base64_encode( const unsigned char * bindata, char * base64, int binlength )13 {14 int i, j;15 unsigned char current;16 17 for ( i = 0, j = 0 ; i < binlength ; i += 3 )18 {19 current = (bindata[i] >> 2) ;20 current &= (unsigned char)0x3F;21 base64[j++] = base64char[(int)current];22 23 current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;24 if ( i + 1 >= binlength )25 {26 base64[j++] = base64char[(int)current];27 base64[j++] = ‘=‘;28 base64[j++] = ‘=‘;29 break;30 }31 current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );32 base64[j++] = base64char[(int)current];33 34 current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;35 if ( i + 2 >= binlength )36 {37 base64[j++] = base64char[(int)current];38 base64[j++] = ‘=‘;39 break;40 }41 current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );42 base64[j++] = base64char[(int)current];43 44 current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;45 base64[j++] = base64char[(int)current];46 }47 base64[j] = ‘\0‘;48 return base64;49 }50 51 int base64_decode( const char * base64, unsigned char * bindata )52 {53 int i, j;54 unsigned char k;55 unsigned char temp[4];56 for ( i = 0, j = 0; base64[i] != ‘\0‘ ; i += 4 )57 {58 memset( temp, 0xFF, sizeof(temp) );59 for ( k = 0 ; k < 64 ; k ++ )60 {61 if ( base64char[k] == base64[i] )62 temp[0]= k;63 }64 for ( k = 0 ; k < 64 ; k ++ )65 {66 if ( base64char[k] == base64[i+1] )67 temp[1]= k;68 }69 for ( k = 0 ; k < 64 ; k ++ )70 {71 if ( base64char[k] == base64[i+2] )72 temp[2]= k;73 }74 for ( k = 0 ; k < 64 ; k ++ )75 {76 if ( base64char[k] == base64[i+3] )77 temp[3]= k;78 }79 80 bindata[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) |81 ((unsigned char)((unsigned char)(temp[1]>>4)&0x03));82 if ( base64[i+2] == ‘=‘ )83 break;84 85 bindata[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) |86 ((unsigned char)((unsigned char)(temp[2]>>2)&0x0F));87 if ( base64[i+3] == ‘=‘ )88 break;89 90 bindata[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) |91 ((unsigned char)(temp[3]&0x3F));92 }93 return j;94 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。