を高め、 transform_width
は完全なbase64エンコーダ/デコーダではありません。 Base64は4ビットの24ビット(3バイト)のグループを表し、それぞれ6ビットをエンコードします。入力データがこのような3バイトグループの整数倍でない場合、それは1つまたは2つのゼロバイトで埋められなければならない。追加されたパディングバイトの数を示すには、符号化された文字列に1つまたは2つの=
文字が追加されます。
transform_width
(これは8ビット2進数から6ビット整数への変換に責任を負う)は、このパディングを自動的に適用しません。これはユーザーが行います。簡単な例:BASE64出力をきれいにフォーマットされ、改行とBASE64入力を復号することができるように、私は、insert_linebreaks
とremove_whitespace
イテレータを添加
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
#include <boost/archive/iterators/remove_whitespace.hpp>
#include <iostream>
#include <string>
using namespace boost::archive::iterators;
using namespace std;
int main(int argc, char **argv) {
typedef transform_width< binary_from_base64<remove_whitespace<string::const_iterator> >, 8, 6 > it_binary_t;
typedef insert_linebreaks<base64_from_binary<transform_width<string::const_iterator,6,8> >, 72 > it_base64_t;
string s;
getline(cin, s, '\n');
cout << "Your string is: '"<<s<<"'"<<endl;
// Encode
unsigned int writePaddChars = (3-s.length()%3)%3;
string base64(it_base64_t(s.begin()),it_base64_t(s.end()));
base64.append(writePaddChars,'=');
cout << "Base64 representation: " << base64 << endl;
// Decode
unsigned int paddChars = count(base64.begin(), base64.end(), '=');
std::replace(base64.begin(),base64.end(),'=','A'); // replace '=' by base64 encoding of '\0'
string result(it_binary_t(base64.begin()), it_binary_t(base64.end())); // decode
result.erase(result.end()-paddChars,result.end()); // erase padding '\0' characters
cout << "Decoded: " << result << endl;
return 0;
}
注意。これらはオプションです。別のパディングを必要と異なる入力文字列と
ラン:
$ ./base64example
Hello World!
Your string is: 'Hello World!'
Base64 representation: SGVsbG8gV29ybGQh
Decoded: Hello World!
$ ./base64example
Hello World!!
Your string is: 'Hello World!!'
Base64 representation: SGVsbG8gV29ybGQhIQ==
Decoded: Hello World!!
$ ./base64example
Hello World!!!
Your string is: 'Hello World!!!'
Base64 representation: SGVsbG8gV29ybGQhISE=
Decoded: Hello World!!!
あなたはこのonline-encoder/decoderでbase64で文字列を確認することができます。
Boost C++ライブラリを使用したBase64エンコーディング関数:http://stackoverflow.com/questions/34680998/attempt-to-decode-a-value-not-in-base64-char-set – ap6491