Base64基础实现

大致说明:
数据按每6位[0,63]进行拆分
将拆分后的数值对应编码成64个可见字符
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"



1
#include <iostream> 2 3 using namespace std; 4 5 class Base64 6 { 7 static char * base64Table; 8 static char resTable[128]; 9 static char retStr[7]; 10 static char retNum[5]; 11 12 static char getTable(char c) 13 { 14 if(resTable['A'] == 0) 15 { 16 for(int i = 0; i < 64; ++i) 17 resTable[(int)base64Table[i]] = i; 18 } 19 return resTable[(int)c]; 20 } 21 static char * longToStr(int val) 22 { 23 for(int i = 0; i < 6; ++i) 24 { 25 retStr[i] = base64Table[val & 0x3F]; 26 val >>= 6; 27 } 28 return retStr; 29 } 30 static char * strToLong(const char * str) 31 { 32 *(int*)retNum = 0; 33 for(int i = 5; i >= 0; --i) 34 { 35 *(int*)retNum <<= 6; 36 *(int*)retNum |= getTable(str[i]); 37 } 38 return &retNum[0]; 39 } 40 public: 41 static std::string base64_encode(const std::string &input) 42 { 43 int inputLen = (input.size() + 3) / 4 * 4; 44 char buffer[inputLen] = {0}; 45 input.copy(buffer, input.size()); 46 47 std::string output; 48 for(int i = 0; i < inputLen / 4; ++i) 49 { 50 output += longToStr(*((unsigned int *)&buffer[i*4])); 51 } 52 return output; 53 } 54 static std::string base64_decode(const std::string &input) 55 { 56 int inputLen = (input.size() + 5) / 6 * 6; 57 char buffer[inputLen] = {0}; 58 input.copy(buffer, input.size()); 59 60 std::string output; 61 for(int i = 0; i < inputLen / 6; ++i) 62 { 63 output += std::string(strToLong(&buffer[i*6]), 4); 64 } 65 return output; 66 } 67 }; 68 char * Base64::base64Table = (char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 69 char Base64::resTable[128] = {0}; 70 char Base64::retStr[7] = {0}; 71 char Base64::retNum[5] = {0}; 72 73 74 75 int main() 76 { 77 // 任意类型数据都ok,用std::string((char*)str, len)构造就OK; 78 std::string str = "1234567"; 79 auto encStr = Base64::base64_encode(str); 80 cout << encStr.size() << ":" << encStr << endl; 81 auto decStr = Base64::base64_decode(encStr); 82 cout << decStr.size() << ":" << decStr << endl; 83 return 0; 84 }

 

posted @ 2021-05-06 16:20  zyh123101  阅读(70)  评论(0编辑  收藏  举报