Created
February 10, 2016 05:26
-
-
Save mmitou/4434555399b7261c0185 to your computer and use it in GitHub Desktop.
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
| #include <stdio.h> | |
| #include <stdbool.h> | |
| #include <stdint.h> | |
| static const size_t num_of_chunk_bits = 6; | |
| static const char base64_conversion_table[64] = { | |
| 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', | |
| 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', | |
| '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' | |
| }; | |
| bool base64_quadruplicate(char buf[4], const char input_data[3], const size_t length_of_data) { | |
| if(length_of_data == 0 || length_of_data > 4) { | |
| return false; | |
| } | |
| char data[3] = {0, 0, 0}; | |
| for(size_t i = 0; i < length_of_data; ++i) { | |
| data[i] = input_data[i]; | |
| } | |
| buf[0] = base64_conversion_table[(0xfc & data[0]) >> 2]; | |
| buf[1] = base64_conversion_table[((0x03 & data[0]) << 4) + ((0xf0 & data[1]) >> 4)]; | |
| buf[2] = base64_conversion_table[((0x0f & data[1]) << 2) + ((0xc0 & data[2]) >> 6)]; | |
| buf[3] = base64_conversion_table[0x3f & data[2]]; | |
| for(int i = 3; length_of_data < i; --i) { | |
| buf[i] = '='; | |
| } | |
| return true; | |
| } | |
| bool base64(char *buf, const char *data, const size_t length) { | |
| int buf_count = 0; | |
| for(size_t data_count = 0; data_count < length; data_count += 3) { | |
| if((data_count != 0) && ((((data_count/3) * 4) % 76) == 0)) { | |
| buf[buf_count] = '\n'; | |
| buf_count++; | |
| } | |
| int rest = length - data_count; | |
| int n = rest < 3 ? rest : 3; | |
| base64_quadruplicate(&buf[buf_count], &data[data_count], n); | |
| buf_count +=4; | |
| } | |
| buf[buf_count] = '\0'; | |
| return true; | |
| } | |
| int main() { | |
| // char xs[] = "ABCDEFG"; | |
| char xs[] = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; | |
| char buf[BUFSIZ]; | |
| base64(buf, xs, sizeof(xs) - 1); | |
| printf("%s\n", buf); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment