Advertisement
OmegaFoxie

String to Base64

Dec 3rd, 2016
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. char* strToBase64(char* input, size_t size_in)
  4. {
  5.     char base64char[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6.     char padding = '=';
  7.  
  8.     unsigned int storage = 0;
  9.     // storage unit for converting 3 * 8 bits to 4 * 6 bits
  10.  
  11.     size_t size_out = (size_in % 3) ? 4 * ((size_in / 3) + 1) : 4 * (size_in / 3);
  12.     // rounding up integer division of 4 * (n / 3) to calculate size of Base64 string
  13.  
  14.     char* base64str = new char[size_out + 1]();
  15.     // allocate enough memory to hold the Base64 string
  16.  
  17.     for (int i = 0; i < (size_out / 4); ++i)
  18.     {
  19.         for (int c = 0; c < 3; ++c) { storage = (storage << CHAR_BIT) | input[(i * 3) + c]; }
  20.         // place 3 * 8 bits into storage unit
  21.  
  22.         for (int c = 0; c < 4; ++c) { base64str[(i * 4) + c] = base64char[((storage << c * 6) >> 18) & 63]; }
  23.         // place 4 * 6 bits into Base64 string
  24.  
  25.         for (int c = 0; c < (((size_in % 3) != 0) ? (3 - (size_in % 3)) : 0); ++c) { base64str[size_out - 1 - c] = padding; }
  26.         // add padding to string
  27.     }
  28.     return base64str;
  29. }
  30.  
  31. int main()
  32. {
  33.     char inputstr[] = "Hello World!";
  34.     // Your input string here
  35.  
  36.     char* output = strToBase64(inputstr, (sizeof(inputstr) - 1));
  37.     // - 1 is only required if the string is null-terminated!
  38.  
  39.     std::cout << output << '\n';
  40.     // Base64 string gets printed here
  41.  
  42.     delete[] output;
  43.     // delete base64str created in strToBase64()
  44.  
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement