Skip to content
TheChatArchiveThe Chat Archive
Coherecommand-a-03-2025· CohereHugging Face LMArena Human Preference 140K

Create a base64 encoder and decoder from scratch using C (standard 99)

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-haiku-20241022’s answer.
  1. User

    Create a base64 encoder and decoder from scratch using C (standard 99)

  2. Cohere Assistant

    Below is a C implementation of a base64 encoder and decoder from scratch, adhering to the C99 standard. The code includes functions to encode and decode strings using the base64 algorithm.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdint.h>
    
    // Base64 encoding characters
    const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    
    // Encode 3 bytes into 4 base64 characters
    void base64_encode_block(const uint8_t *input, char *output) {
        output[0] = base64_chars[(input[0] & 0xFC) >> 2];
        output[1] = base64_chars[((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4)];
        output[2] = base64_chars[((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6)];
        output[3] = base64_chars[input[2] & 0x3F];
    }
    
    // Base64 encode a buffer
    char *base64_encode(const uint8_t *data, size_t input_length, size_t *output_length) {
        if (input_length == 0) {
            *output_length = 0;
            return NULL;
        }
    
        *output_length = 4 * ((input_length + 2) / 3);
        char *encoded_data = (char *)malloc(*output_length + 1); // +1 for null terminator
        if (!encoded_data) {
            return NULL;
        }
    
        size_t i, j = 0;
        for (i = 0; i < input_length - 2; i += 3) {
            base64_encode_block(data + i, encoded_data + j);
            j += 4;
        }
    
        // Handle padding
        if (input_length % 3) {
            uint8_t temp[3] = {0};
            memcpy(temp, data + i, input_length % 3);
            base64_encode_block(temp, encoded_data + j);
            j += 4;
    
            // Add padding characters
            while (j < *output_length) {
                encoded_data[j++] = '=';
            }
        }
    
        encoded_data[*output_length] = '\0'; // Null terminate the string
        return encoded_data;
    }
    
    // Decode a single base64 character
    int base64_decode_char(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; // Invalid character
    }
    
    // Decode 4 base64 characters into 3 bytes
    int base64_decode_block(const char *input, uint8_t *output) {
        int values[4];
        for (int i = 0; i < 4; i++) {
            values[i] = base64_decode_char(input[i]);
            if (values[i] == -1 && input[i] != '=') {
                return 0; // Invalid input
            }
        }
    
        output[0] = (values[0] << 2) | (values[1] >> 4);
        output[1] = (values[1] << 4) | (values[2] >> 2);
        output[2] = (values[2] << 6) | values[3];
    
        // Handle padding
        if (input[2] == '=') {
            return 1; // One byte
        } else if (input[3] == '=') {
            return 2; // Two bytes
        } else {
            return 3; // Three bytes
        }
    }
    
    // Base64 decode a string
    uint8_t *base64_decode(const char *data, size_t input_length, size_t *output_length) {
        if (input_length == 0 || input_length % 4 != 0) {
            *output_length = 0;
            return NULL;
        }
    
        *output_length = 3 * (input_length / 4);
        uint8_t *decoded_data = (uint8_t *)malloc(*output_length);
        if (!decoded_data) {
            return NULL;
        }
    
        size_t j = 0;
        for (size_t i = 0; i < input_length; i += 4) {
            int bytes_written = base64_decode_block(data + i, decoded_data + j);
            if (bytes_written == 0) {
                free(decoded_data);
                *output_length = 0;
                return NULL;
            }
            j += bytes_written;
        }
    
        *output_length = j; // Adjust for padding
        return decoded_data;
    }
    
    // Example usage
    int main() {
        const char *input_str = "Hello, World!";
        size_t encoded_length, decoded_length;
    
        // Encode
        char *encoded_str = base64_encode((const uint8_t *)input_str, strlen(input_str), &encoded_length);
        if (encoded_str) {
            printf("Encoded: %s\n", encoded_str);
            free(encoded_str);
        }
    
        // Decode
        uint8_t *decoded_str = base64_decode("SGVsbG8sIFdvcmxkIQ==", strlen("SGVsbG8sIFdvcmxkIQ=="), &decoded_length);
        if (decoded_str) {
            decoded_str[decoded_length] = '\0'; // Null terminate for printing
            printf("Decoded: %s\n", decoded_str);
            free(decoded_str);
        }
    
        return 0;
    }
    

    Explanation:

    1. Base64 Encoding:

      • The base64_encode_block function encodes 3 bytes into 4 base64 characters.
      • The base64_encode function handles the entire input buffer, including padding with = characters when necessary.
    2. Base64 Decoding:

      • The base64_decode_char function converts a base64 character back to its index.
      • The base64_decode_block function decodes 4 base64 characters into 3 bytes, handling padding.
      • The base64_decode function processes the entire input string, adjusting the output length based on padding.
    3. Memory Management:

      • Both encoding and decoding functions allocate memory for the output, which must be freed by the caller.
    4. Example Usage:

      • The main function demonstrates encoding and decoding a sample string.

    Notes:

    • The code assumes valid input for simplicity. Additional error checking can be added for production use.
    • The decoder expects a valid base64 string with correct padding. Invalid characters or incorrect padding will result in errors.

    Compile the code with a C99-compliant compiler, e.g., gcc -std=c99 -o base64 base64.c.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.