Create a base64 encoder and decoder from scratch using C (standard 99)
- User
Create a base64 encoder and decoder from scratch using C (standard 99)
Assistant
I'll help you create a base64 encoder and decoder in C (standard C99). I'll provide a complete implementation with explanations.
#include <stdio.h> #include <stdlib.h> #include <string.h> // Base64 encoding character set static const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Reverse lookup for decoding static int base64_char_to_index(char c) { if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; if (c >= '0' && c <= '9') return c - '0' + 52; if (c == '+') return 62; if (c == '/') return 63; return -1; } // Base64 Encoder char* base64_encode(const unsigned char* input, size_t input_length, size_t* output_length) { size_t output_required_length = 4 * ((input_length + 2) / 3); char* output = malloc(output_required_length + 1); if (!output) return NULL; size_t i, j; for (i = 0, j = 0; i < input_length; ) { // Get 3 input bytes unsigned int octet_a = i < input_length ? input[i++] : 0; unsigned int octet_b = i < input_length ? input[i++] : 0; unsigned int octet_c = i < input_length ? input[i++] : 0; // Combine into 24-bit number unsigned int triple = (octet_a << 16) | (octet_b << 8) | octet_c; // Split into 4 base64 characters output[j++] = base64_chars[(triple >> 18) & 0x3F]; output[j++] = base64_chars[(triple >> 12) & 0x3F]; output[j++] = base64_chars[(triple >> 6) & 0x3F]; output[j++] = base64_chars[triple & 0x3F]; } // Padding if (input_length % 3 == 1) { output[j-2] = '='; output[j-1] = '='; } else if (input_length % 3 == 2) { output[j-1] = '='; } output[j] = '\0'; *output_length = j; return output; } // Base64 Decoder unsigned char* base64_decode(const char* input, size_t input_length, size_t* output_length) { if (input_length % 4 != 0) return NULL; size_t output_required_length = input_length / 4 * 3; unsigned char* output = malloc(output_required_length + 1); if (!output) return NULL; size_t i, j; for (i = 0, j = 0; i < input_length; ) { // Get 4 base64 characters int char_a = base64_char_to_index(input[i++]); int char_b = base64_char_to_index(input[i++]); int char_c = base64_char_to_index(input[i++]); int char_d = base64_char_to_index(input[i++]); // Validate input if (char_a == -1 || char_b == -1 || char_c == -1 || char_d == -1) { free(output); return NULL; } // Reconstruct 24-bit number unsigned int triple = (char_a << 18) | (char_b << 12) | (char_c << 6) | char_d; // Split into 3 bytes output[j++] = (triple >> 16) & 0xFF; // Handle padding if (input[i-1] != '=') { output[j++] = (triple >> 8) & 0xFF; if (input[i-2] != '=') { output[j++] = triple & 0xFF; } } } output[j] = '\0'; *output_length = j; return output; } // Example usage int main() { // Test encoding const char* test_input = "Hello, World!"; size_t input_length = strlen(test_input); size_t encoded_length; char* encoded = base64_encode((unsigned char*)test_input, input_length, &encoded_length); printf("Encoded: %s\n", encoded); // Test decoding size_t decoded_length; unsigned char* decoded = base64_decode(encoded, encoded_length, &decoded_length); printf("Decoded: %s\n", decoded); // Cleanup free(encoded); free(decoded); return 0; }This implementation follows the Base64 encoding standard with the following key features:
-
Encoding Process:
- Takes input bytes and converts them into base64 characters
- Handles input lengths not divisible by 3 with padding ('=')
- Uses bitwise operations to split 24-bit groups into 4 6-bit characters
-
Decoding Process:
- Converts base64 characters back to original bytes
- Handles padding and validates input characters
- Reconstructs original bytes using bitwise operations
-
Key Functions:
base64_encode(): Converts binary data to base64 stringbase64_decode(): Converts base64 string back to binary database64_char_to_index(): Helps with character to index mapping
Notes:
- Uses dynamic memory allocation
- Handles memory errors
- Null-terminates output strings
- Provides length tracking for both encoded and decoded data
Compilation:
gcc -std=c99 base64.c -o base64The code provides a complete, from-scratch implementation of Base64 encoding and decoding in standard C99. It includes error handling, dynamic memory management, and a simple example in the
main()function.Would you like me to elaborate on any part of the implementation?
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.