Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- char* strToBase64(char* input, size_t size_in)
- {
- char base64char[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- char padding = '=';
- unsigned int storage = 0;
- // storage unit for converting 3 * 8 bits to 4 * 6 bits
- size_t size_out = (size_in % 3) ? 4 * ((size_in / 3) + 1) : 4 * (size_in / 3);
- // rounding up integer division of 4 * (n / 3) to calculate size of Base64 string
- char* base64str = new char[size_out + 1]();
- // allocate enough memory to hold the Base64 string
- for (int i = 0; i < (size_out / 4); ++i)
- {
- for (int c = 0; c < 3; ++c) { storage = (storage << CHAR_BIT) | input[(i * 3) + c]; }
- // place 3 * 8 bits into storage unit
- for (int c = 0; c < 4; ++c) { base64str[(i * 4) + c] = base64char[((storage << c * 6) >> 18) & 63]; }
- // place 4 * 6 bits into Base64 string
- for (int c = 0; c < (((size_in % 3) != 0) ? (3 - (size_in % 3)) : 0); ++c) { base64str[size_out - 1 - c] = padding; }
- // add padding to string
- }
- return base64str;
- }
- int main()
- {
- char inputstr[] = "Hello World!";
- // Your input string here
- char* output = strToBase64(inputstr, (sizeof(inputstr) - 1));
- // - 1 is only required if the string is null-terminated!
- std::cout << output << '\n';
- // Base64 string gets printed here
- delete[] output;
- // delete base64str created in strToBase64()
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement