在Qt中,在网络通信时,有时需要将16进制字节流转换为Base64编码传输,在Qt的QByteArray类中,提供了与Base64转换的接口:
//16进制字节流转为Base64
QByteArray toBase64(Base64Options options) const;
QByteArray toBase64() const; // ### Qt6 merge with previous
//Base64转为16进制字节流
static QByteArray fromBase64(const QByteArray &base64, Base64Options options);
static QByteArray fromBase64(const QByteArray &base64); // ### Qt6 merge with previous
测试代码如下:
#include
#include
#include
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
char hexData[10]={0x1, 0x2, 0x3,0x4, 0x5,0x6,0x7,0x8,0x9,0xa};
QByteArray data = QByteArray(hexData, 10);
//hex数据转换为base64编码,转换后赋值给base64Str
QString base64Str = data.toBase64();
//QByteArray::toHex(); //是将十六进制数据,按照其字面值转换为字符串,比如: 0x12-->0x31 0x32,以字符串输出时就是“12”
qDebug()<
QByteArray decBase64 = QByteArray::fromBase64(QString(base64Str).toLatin1());
qDebug()<
return a.exec();
}
执行结果:
hexData: "0102030405060708090a" , base64: "AQIDBAUGBwgJCg=="
hexData: "0102030405060708090a"