C++求助 字符串遇到 0x00
小弟有一段unsigned char代码172,237,5,51,0,172,237,5,51,172,237,5,51,172,237,0,0,5,51,172,237,5,51...(非常长)需要BASE64编码 在编码中发现unsigned char中只要当前char是0就会停住退出 寻求帮助,如何才能把0也给编码
运行结果
rO0FMxY= //{172,237,5,51}
rO0FMw== //{172,237,5,51,0}
rO0FMw== //{172,237,5,51,0,172,237,5,51,172,237,5,51,172,237,5,51,172,237,5,51} 后面的全部不编码了
现遇到困难 遇到0就被截断 寻求老师傅指教
程序代码:
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <string.h> using namespace std; // 全局常量定义 const char* base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const char padding_char = '='; /*编码代码 * const unsigned char * sourcedata, 源数组 * char * base64 ,码字保存 */ int base64_encode(const unsigned char* sourcedata, char* base64) { int i = 0, j = 0; unsigned char trans_index = 0; // 索引是8位,但是高两位都为0 const int datalength = strlen((const char*)sourcedata); for (; i < datalength; i += 3) { // 每三个一组,进行编码 // 要编码的数字的第一个 trans_index = ((sourcedata[i] >> 2) & 0x3f); base64[j++] = base64char[(int)trans_index]; // 第二个 trans_index = ((sourcedata[i] << 4) & 0x30); if (i + 1 < datalength) { trans_index |= ((sourcedata[i + 1] >> 4) & 0x0f); base64[j++] = base64char[(int)trans_index]; } else { base64[j++] = base64char[(int)trans_index]; base64[j++] = padding_char; base64[j++] = padding_char; break; // 超出总长度,可以直接break } // 第三个 trans_index = ((sourcedata[i + 1] << 2) & 0x3c); if (i + 2 < datalength) { // 有的话需要编码2个 trans_index |= ((sourcedata[i + 2] >> 6) & 0x03); base64[j++] = base64char[(int)trans_index]; trans_index = sourcedata[i + 2] & 0x3f; base64[j++] = base64char[(int)trans_index]; } else { base64[j++] = base64char[(int)trans_index]; base64[j++] = padding_char; break; } } base64[j] = '\0'; return 0; } int main() { //unsigned char no0in[] = {172,237,5,51}; unsigned char n0[] = {172,237,5,51}; char n0o[1024]; base64_encode(n0,n0o); printf("%s\n",n0o); unsigned char n0in[] = {172,237,5,51,0}; char n0out[1024]; base64_encode(n0in,n0out); printf("%s\n",n0out); unsigned char y0in[] = {172,237,5,51,0,172,237,5,51,172,237,5,51,172,237,5,51,172,237,5,51}; char y0out[1024]; base64_encode(y0in,y0out); printf("%s\n",y0out); }