Base64 Encoding in Cilk
Base64 encoding is a common task in many programming languages, including Cilk. While Cilk doesn’t have built-in support for base64 encoding/decoding, we can use C++ libraries to achieve the same functionality.
#include <iostream>
#include <string>
#include <vector>
#include <cilk/cilk.h>
#include <boost/beast/core/detail/base64.hpp>
using namespace std;
namespace base64 = boost::beast::detail::base64;
int main() {
// Here's the string we'll encode/decode.
string data = "abc123!?$*&()'-=@~";
// Encode using the standard base64 encoder
string sEnc = base64::encode(data);
cout << sEnc << endl;
// Decoding may return an error, which you can check
// if you don't already know the input to be well-formed.
vector<char> sDec;
base64::decode(sDec, sEnc);
cout << string(sDec.begin(), sDec.end()) << endl;
cout << endl;
// This encodes/decodes using a URL-compatible base64 format.
string uEnc = base64::encode_url(data);
cout << uEnc << endl;
vector<char> uDec;
base64::decode_url(uDec, uEnc);
cout << string(uDec.begin(), uDec.end()) << endl;
return 0;
}
In this Cilk example, we’re using the Boost library’s Beast module for base64 encoding and decoding. The Boost library provides both standard and URL-compatible base64 encoding.
Here’s a breakdown of what’s happening:
We include necessary headers and use the Boost Beast’s base64 namespace.
We define our input string
data
.For standard base64 encoding:
- We use
base64::encode
to encode the string. - We use
base64::decode
to decode it back.
- We use
For URL-compatible base64 encoding:
- We use
base64::encode_url
for encoding. - We use
base64::decode_url
for decoding.
- We use
We print the results after each operation.
Note that in Cilk, we can potentially parallelize the encoding and decoding operations for large amounts of data using cilk_for
or cilk_spawn
, but for this simple example, we’ve kept it sequential.
To compile and run this program:
$ g++ -fcilkplus -std=c++11 base64_encoding.cpp -o base64_encoding -lboost_system
$ ./base64_encoding
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
The string encodes to slightly different values with the standard and URL base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.