Qt hexadecimal byte stream into Base64 encoding

In Qt, when the network communication is sometimes necessary to hexadecimal byte stream to Base64 encoded and transmitted in QByteArray class Qt is provided with Base64 interface conversion:

//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

Test code is as follows:

#include <QCoreApplication>
#include <QCryptographicHash>
#include <QDebug>

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()<<"hexData: "<<data.toHex()<<", base64: "<<base64Str;

    QByteArray decBase64 = QByteArray::fromBase64(QString(base64Str).toLatin1());
    qDebug()<<"hexData: "<<decBase64;

    return a.exec();
}

Results of the:

hexData:  "0102030405060708090a" , base64:  "AQIDBAUGBwgJCg=="
hexData:  "0102030405060708090a"

Micro-channel public number:

Published 42 original articles · won praise 40 · views 40000 +

Guess you like

Origin blog.csdn.net/wuquan_1230/article/details/104413197