Created
August 4, 2023 03:30
-
-
Save rendon/842e8f7563b99356981c6425a65c67ae to your computer and use it in GitHub Desktop.
Basic Base64 encoding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reference: https://en.wikipedia.org/wiki/Base64 | |
#include <bits/stdc++.h> | |
using namespace std; | |
const char* alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
int getValue(char c) { | |
int len = strlen(alphabet); | |
for (int i = 0; i < len; i++) { | |
if (c == alphabet[i]) { return i; } | |
} | |
return -1; | |
} | |
string encode(string str) { | |
string bits; | |
for (char c : str) { | |
int x = c; | |
for (int i = 7; i >= 0; i--) { | |
if (x & (1<<i)) { | |
bits += '1'; | |
} else { | |
bits += '0'; | |
} | |
} | |
} | |
while (bits.size() % 6 != 0) { | |
bits += '0'; | |
} | |
string encoded; | |
for (int i = 0; i < bits.size(); i += 6) { | |
int v = 0; | |
for (int j = 0; j < 6; j++) { | |
v = v * 2 + (bits[i+j] - '0'); | |
} | |
encoded += alphabet[v]; | |
} | |
while (encoded.size() % 4 != 0) { | |
encoded += "="; | |
} | |
return encoded; | |
} | |
string tobin(int v) { | |
string bits; | |
while (v > 0) { | |
bits += char(v % 2 + '0'); | |
v /= 2; | |
} | |
while (bits.size() < 6) { | |
bits += '0'; | |
} | |
reverse(begin(bits), end(bits)); | |
return bits; | |
} | |
string decode(string str) { | |
string bits; | |
for (int i = 0; i < str.size(); i++) { | |
if (str[i] == '=') { break; } | |
int v = getValue(str[i]); | |
bits += tobin(v); | |
} | |
string decoded; | |
for (int i = 0; i < bits.size(); i += 8) { | |
int c = 0; | |
for (int j = 0; j < 8 && i + j < bits.size(); j++) { | |
c = c * 2 + (bits[i+j] - '0'); | |
} | |
if (c > 0) { | |
decoded += char(c); | |
} | |
} | |
return decoded; | |
} | |
int main() { | |
vector<string> examples{ | |
"Many hands make light work.", | |
"Man", | |
"Ma", | |
"M", | |
"light work.", | |
"light work", | |
"light wor", | |
"light wo", | |
"light w" | |
}; | |
for (auto& example : examples) { | |
string enc = encode(example); | |
cout << "Example: " << example << "\n"; | |
cout << "Encoded: " << enc << "\n"; | |
cout << "Decoded: " << decode(enc) << "\n\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment