Base64 encoding and decoding using Qt 5 framework

Hi everyone!

In one of my previous posts, we had learnt how to configure and setup Qt for Windows. Base64 is basically a method using which we can encode binary data into a character set in order to transmit the data without any loss or modification of the contents. It is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Base64-encoding is a way to encode 8 bit character data in a series of 6 bit characters. This was mostly used in transferring of data across 6 or 7 bit connections. On the other hand Base64-decoding helps us to get back the original text. Through this post, we will learn how to use the Qt framework to implement Base64 encoding and decoding.

Pre-requisites: Qt creator for Windows (64 bit), MinGW or VS compiler

Launch Qt Creator and create a new Qt console application project called QtEncodingExample. Choose the default Desktop kit and add the following code in the main.cpp file!

main.cpp

#include <QCoreApplication>
#include <QString>
#include <QDebug>
#include <QByteArray>

QString base64_encode(QString string);
QString base64_decode(QString string);

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString srcString = "Hello";
    QString encodedString = base64_encode(srcString);
    QString decodedString = base64_decode(encodedString);

    qDebug() << "Encoded string is" << encodedString;
    qDebug() << "Decoded string is" << decodedString;
    return a.exec();
}

QString base64_encode(QString string){
    QByteArray ba;
    ba.append(string);
    return ba.toBase64();
}

QString base64_decode(QString string){
    QByteArray ba;
    ba.append(string);
    return QByteArray::fromBase64(ba);
}

.pro file

QT  += core
QT  -= gui
TARGET = QtEncodingExample
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app
SOURCES += main.cpp

Save all changes. Build and run the application. If no errors occur, you should see the following output!

qt_base64_example