base64编解码(一)
ZBase64.h
#include <string>
using namespace std;
class ZBase64
{
public:
/*编码
DataByte
[in]输入的数据长度,以字节为单位
*/
string Encode(const unsigned char* Data,int DataByte);
/*解码
DataByte
[in]输入的数据长度,以字节为单位
OutByte
[out]输出的数据长度,以字节为单位,请不要通过返回值计算
输出数据的长度
*/
string Decode(const char* Data,int DataByte,int& OutByte);
};
ZBase64.cpp
#include "../hpp/ZBase64.h"
string ZBase64::Encode(const unsigned char* Data,int DataByte)
{
//编码表
const char EncodeTable[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//返回值
string strEncode;
unsigned char Tmp[4]={0};
int LineLength=0;
for(int i=0;i<(int)(DataByte / 3);i++)
{
Tmp[1] = *Data++;
Tmp[2] = *Data++;
Tmp[3] = *Data++;
strEncode+= EncodeTable[Tmp[1] >> 2];
strEncode+= EncodeTable[((Tmp[1] << 4) | (Tmp[2] >> 4)) & 0x3F];
strEncode+= EncodeTable[((Tmp[2] << 2) | (Tmp[3] >> 6)) & 0x3F];
strEncode+= EncodeTable[Tmp[3] & 0x3F];
if(LineLength+=4,LineLength==76) {strEncode+="\r\n";LineLength=0;}
}
//对剩余数据进行编码
int Mod=DataByte % 3;
if(Mod==1)
{
Tmp[1] = *Data++;
strEncode+= EncodeTable[(Tmp[1] & 0xFC) >> 2];
strEncode+= EncodeTable[((Tmp[1] & 0x03) << 4)];
strEncode+= "==";
}
else if(Mod==2)
{
Tmp[1] = *Data++;
Tmp[2] = *Data++;
strEncode+= EncodeTable[(Tmp[1] & 0xFC) >> 2];
strEncode+= EncodeTable[((Tmp[1] & 0x03) << 4) | ((Tmp[2] & 0xF0) >> 4)];
strEncode+= EncodeTable[((Tmp[2] & 0x0F) << 2)];
strEncode+= "=";
}
return strEncode;
}
string ZBase64::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'
};
//返回值
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;
}
使用示例(结合CxImage库):
CString CScanDlg::EncodeImage()
{//对图片进行Base64编码
ZBase64 zBase;
//图片编码
CxImage image; // 定义一个CxImage对象
image.Load(this->m_strImgPath, CXIMAGE_FORMAT_JPG); //先装载jpg文件,需要指定文件类型
long size=0;//得到图像大小
BYTE* buffer=0;//存储图像数据的缓冲
image.Encode(buffer,size,CXIMAGE_FORMAT_JPG);//把image对象中的图像以type类型数据copy到buffer
string strTmpResult=zBase.Encode(buffer,size);
CString result;
result = strTmpResult.c_str();
return result;
}
void CScanDlg::DecodeImageData(CString strData)
{//对Base64编码过的数据解码并显示原图片
ZBase64 zBase;
int OutByte=0;
string strTmpResult=zBase.Decode(strData,strData.GetLength(),OutByte);
int i,len = strTmpResult.length();
BYTE *buffer = new BYTE[len];
for (i=0;i<len;++i)
{
buffer[i] = strTmpResult[i];
}
CxImage image(buffer,len,CXIMAGE_FORMAT_JPG);//把内存缓冲buffer中的数据构造成Image对象
delete [] buffer;
CDC* hdc = m_picture.GetDC();
m_bitmap = image.MakeBitmap(hdc->m_hDC);
HBITMAP h0ldBmp = m_picture.SetBitmap(m_bitmap);
if(h0ldBmp) DeleteObject(h0ldBmp);
if(hdc->m_hDC) m_picture.ReleaseDC(hdc);
if(m_bitmap) DeleteObject(m_bitmap);
}
ZBase64 zBase64;
int OutByte=0;
string data = chunk;
string dstData_base64 = zBase64.Decode(chunk,data.length() , OutByte);
base64编解码(二)
base64util.h
#include <string>
using namespace std;
class base64util {
public:
enum Base64Option {
Base64Encoding = 0,
Base64UrlEncoding = 1,
KeepTrailingEquals = 0,
OmitTrailingEquals = 2
};
//对数据的base64解密 参数sourceData代表要被解密的数据, options表示加密选项flags,默认0
std::string decode_base64(const std::string sourceData, int options = Base64Encoding);
//对数据的base64加密 参数sourceData代表要被加密的数据, options表示加密选项flags 默认0
std::string encode_base64(const std::string sourceData, int options = Base64Encoding);
};
base64util.cpp
#include <opencv2/core/hal/interface.h>
#include <assert.h>
#include "../hpp/base64util.h"
std::string base64util::encode_base64(const std::string sourceData, int options) {
const char alphabet_base64[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
"ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
const char alphabet_base64url[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
"ghijklmn" "opqrstuv" "wxyz0123" "456789-_";
const char *const alphabet = options & Base64UrlEncoding ? alphabet_base64url : alphabet_base64;
const char padchar = '=';
int padlen = 0;
std::string tmp;
tmp.resize((sourceData.size() + 2) / 3 * 4);
int i = 0;
char *out = &tmp[0];
while (i < sourceData.size()) {
// encode 3 bytes at a time
int chunk = 0;
chunk |= int(uchar(sourceData.data()[i++])) << 16;
if (i == sourceData.size()) {
padlen = 2;
} else {
chunk |= int(uchar(sourceData.data()[i++])) << 8;
if (i == sourceData.size())
padlen = 1;
else
chunk |= int(uchar(sourceData.data()[i++]));
}
int j = (chunk & 0x00fc0000) >> 18;
int k = (chunk & 0x0003f000) >> 12;
int l = (chunk & 0x00000fc0) >> 6;
int m = (chunk & 0x0000003f);
*out++ = alphabet[j];
*out++ = alphabet[k];
if (padlen > 1) {
if ((options & OmitTrailingEquals) == 0)
*out++ = padchar;
} else {
*out++ = alphabet[l];
}
if (padlen > 0) {
if ((options & OmitTrailingEquals) == 0)
*out++ = padchar;
} else {
*out++ = alphabet[m];
}
}
assert((options & OmitTrailingEquals) || (out == tmp.size() + tmp.data()));
if (options & OmitTrailingEquals)
tmp.resize(out - tmp.data());
return tmp;
}
std::string base64util::decode_base64(std::string sourceData, int options) {
unsigned int buf = 0;
int nbits = 0;
std::string tmp;
tmp.resize((sourceData.size() * 3) / 4);
int offset = 0;
for (int i = 0; i < sourceData.size(); ++i) {
int ch = sourceData.at(i);
int d;
if (ch >= 'A' && ch <= 'Z')
d = ch - 'A';
else if (ch >= 'a' && ch <= 'z')
d = ch - 'a' + 26;
else if (ch >= '0' && ch <= '9')
d = ch - '0' + 52;
else if (ch == '+' && (options & Base64UrlEncoding) == 0)
d = 62;
else if (ch == '-' && (options & Base64UrlEncoding) != 0)
d = 62;
else if (ch == '/' && (options & Base64UrlEncoding) == 0)
d = 63;
else if (ch == '_' && (options & Base64UrlEncoding) != 0)
d = 63;
else
d = -1;
if (d != -1) {
buf = (buf << 6) | d;
nbits += 6;
if (nbits >= 8) {
nbits -= 8;
tmp[offset++] = buf >> nbits;
buf &= (1 << nbits) - 1;
}
}
}
tmp.resize(offset);
return tmp;
}
使用:
std::string srcData = "ABCDEFGHIGKLMN...+++---000123456789~!@#$%^&*()_+";
std::string srcData_base64 = encode_base64(srcData);
std::string dstData_base64 = decode_base64(srcData_base64);
std::cout<< "src data:" << srcData << std::endl;
std::cout<< "to base64:" << srcData_base64 << std::endl;
std::cout <<"from base64:" << dstData_base64 << std::endl;
//url
srcData = "https://mp.csdn.net/postedit/83345819";
srcData_base64 = encode_base64(srcData, Base64UrlEncoding & OmitTrailingEquals);
dstData_base64 = decode_base64(srcData_base64, Base64UrlEncoding & OmitTrailingEquals);
std::cout<< "src data:" << srcData << std::endl;
std::cout<< "to base64:" << srcData_base64 << std::endl;
std::cout <<"from base64:" << dstData_base64 << std::endl;
获得毫秒级的时间差
C++的<time.h>头文件中有time和clock可以用来计算时间,但是中提供了更加精确的统计时间的方法。 下面的代码支持Windows和Linux,但是要求编译器必须支持C++11。
#include <iostream>
#include <chrono>
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
int main()
{
high_resolution_clock::time_point beginTime = high_resolution_clock::now();
...
do some stuff
...
high_resolution_clock::time_point endTime = high_resolution_clock::now();
milliseconds timeInterval = std::chrono::duration_cast<milliseconds>(endTime - beginTime);
std::cout << timeInterval.count() << "ms\n";
}
linux下C++内存泄漏检测
- Valgrind 安装:
sudo apt-get install valgrind`
- 使用
valgrind --tool=memcheck --leak-check=full ./test
valgrind --leak-check=full ./程序名
生成.so文件
- C++生成.so文件
g++ -shared -fPIC -o testso.so testso.cpp
- C 生成.so文件
gcc test_a.c test_b.c test_c.c -fPIC -shared -o libtest.so
C使用gcc编译,C++使用g++编译。
文件操作
程序运行时产生的数据都属于临时数据,程序一旦运行结束都会释放。通过文件可以数据持久化,C++对文件操作需要包含头文<fstream>
文件类型分为两种:
- 文本文件 - 文件以文本的ASCLL码形式存储在计算机中
- 二进制文件 - 文件以文本的二进制形式存储在计算机中,用一般不能直接读懂他们 操作文件的三大类:
- ofstream:写操作
- ifstream:读操作
- fstream:读写操作
文本文件:
写文件步骤:
包含头文件
`#include <fstream>`
创建流对象
`ofstream ofs;`
打开文件
`ofs.open("文件路径",打开方式);`
写数据
`ofs<< "写入的数据";`
关闭文件
`ofs.close();`
文件打开方式:
打开方式 解释
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate c初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在先删除,再创建
ios::binary 二进制方式
注意:
文打开方式可以配合使用,利用|操作符
例如:用二进制方式写文件`ios::binary | ios::out`
#include <fstream>
void test()
{
ofstream ofs;
ofs.open("test.txt",ios::out);
ofs<< "姓名:张三" << endl;
ofs<< "姓名:张三" << endl;
ofs.close();
}