fork download
  1. // Base64EnDe.cpp : アプリケーションのエントリ ポイントを定義します。
  2. //
  3. #include <iostream>
  4. #include <string>
  5. #include <vector>
  6. #include <cstdint>
  7. #include <tuple>
  8.  
  9.  
  10. typedef std::vector<std::uint8_t> DType;
  11. const std::string Token = "ABCDEFGHIJKLNMOPQRSTUVWXYZabcdefghijklnmopqrstuvwxyz0123456789+/";
  12. const std::string Pad = "=";
  13.  
  14. DType Char3Enc4(const std::int16_t& A, const std::int16_t& B, const std::int16_t& C) {
  15. std::uint64_t V1 = 0;
  16. std::uint64_t V2 = 0;
  17. std::uint64_t P = 0;
  18. DType D;
  19. V1 = A;
  20. P = (V1 >> 2) & 0x3f;
  21. D.push_back(P);
  22. V1 &= 3;
  23. V2 = (B<0) ? 0:B;
  24.  
  25. P = ((V1 << 4) & 0x3f) | ((V2 >> 4) & 0x3f);
  26. D.push_back(P);
  27. V1 = V2 - ((V2 >> 4) << 4);
  28. V2 = (C<0) ? 0:C;
  29.  
  30. if (B < 0) return D;
  31.  
  32. P = ((V1 << 2) & 0x3f) | ((V2 >> 6) & 0x3f);
  33. D.push_back(P);
  34. V1 = V2 - ((V2 >> 6) << 6);
  35.  
  36. if (C < 0) return D;
  37.  
  38. P = V1 & 0x3f;
  39. D.push_back(P);
  40.  
  41. return D;
  42. }
  43.  
  44.  
  45. std::string Base64Enc(const std::string& s) {
  46.  
  47. DType D;
  48. DType T;
  49. std::string R;
  50. char A = 0;
  51. char B = 0;
  52. char C = 0;
  53.  
  54.  
  55. for (std::size_t i = 0; i < s.size(); i+=3) {
  56. A = i < s.size() ? s[i]:-1;
  57. B = i+1 < s.size() ? s[i+1]:-1;
  58. C = i+2 < s.size() ? s[i+2]:-1;
  59.  
  60. T = Char3Enc4(A, B, C);
  61. D.insert(D.begin()+D.size(), T.begin(), T.end());
  62. }
  63.  
  64. for (auto& o : D) {
  65. R += Token[o];
  66. }
  67. for (std::size_t i = 0; i < (R.size() % 4); i++) {
  68. R += Pad;
  69. }
  70.  
  71. return R;
  72. }
  73.  
  74.  
  75. int main()
  76. {
  77. std::string S;
  78.  
  79. S = Base64Enc("ABCDEFG");
  80. std::cout << S << std::endl;
  81. return 0;
  82. }
  83.  
Success #stdin #stdout 0s 4548KB
stdin
Standard input is empty
stdout
QUJDREVGRw==