记录C++,base64解码写PDF文件遇到的坑
不得不bb一下,
场景:用户传base64数据,我生成PDF文件保存到指定路径下
背景:在前人写好的工程上增加这个功能,工程中有base64的.h, .cpp 文件,我试了base64编码没有问题,所以在用到解码的时候,我理所当然的认为解码函数也是没问题的,但是每次我写完文件,就发现文件报错损坏打不开。从来没有怀疑过解码函数,一直在测试是不是多字节问题,是不是写文件的方式不对,是不是我太笨了,呜呜呜。最终历时一段时间后,搞定了这个简单的功能,原来是base64解码函数的问题。噗~
base64解码函数:
std::string base64_Decode(const char* Data, int DataByte, int& OutByte) { const char DecodeTable[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, // '+' 0, 0, 0, 63, // '/' 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9' 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z' 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z' }; // ох std::string strDecode; int nValue; int i = 0; while (i < DataByte) { if (*Data != '\r' && *Data != '\n') { nValue = DecodeTable[*Data++] << 18; nValue += DecodeTable[*Data++] << 12; strDecode += (nValue & 0x00FF0000) >> 16; OutByte++; if (*Data != '=') { nValue += DecodeTable[*Data++] << 6; strDecode += (nValue & 0x0000FF00) >> 8; OutByte++; if (*Data != '=') { nValue += DecodeTable[*Data++]; strDecode += nValue & 0x000000FF; OutByte++; } } i += 4; } else { Data++; i++; } } return strDecode; }
传base64解码写文件函数:
void CZZUser::hidBaseToFile(const char* baseData, const char* filePath) { // base64 转 文件 // 解码 int resbase64 = 0; std::string fileData = base64_Decode(baseData, strlen(baseData), resbase64); // 写文件 FILE *f = fopen(filePath, "wb"); fwrite(fileData.c_str(), resbase64, 1, f); fclose(f); }