Initial commit, write base64 encoder

This commit is contained in:
Horseshoe Crab 2022-04-07 17:51:38 -07:00
commit 30411cf844
3 changed files with 82 additions and 0 deletions

0
README.md Normal file
View File

14
set1/Makefile Normal file
View File

@ -0,0 +1,14 @@
CC = gcc
CFLAGS = -Wall -Wpedantic -Wextra -std=c99 -g
RM = rm
all: base64
base64: base64.c
$(CC) -o $@ $^
clean:
$(RM) base64
$(RM) *.o

68
set1/base64.c Normal file
View File

@ -0,0 +1,68 @@
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/*
* base64.c: reads in raw bytes and converts to/outputs in base64 format
* x1phosura 2022
*/
#define BUF_LEN 4096
#define b64_output putchar
//#define b64_output b64_out_debug
size_t out_index = 0;
char out_buf[BUF_LEN];
void b64_out_debug(char c)
{
printf("Using '%c' from base64 alphabet\n", c);
out_buf[out_index] = c; // TODO: check out_index
++out_index;
}
char *b64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void main(int argc, char *argv[])
{
char c, spoke = 0;
int tmp, alph_index = 0;
while ((c = getchar()) != EOF) {
switch (spoke) {
case 0:
alph_index = c >> 2; // get last 6 bits
tmp = (c & 0x03) << 4; // extract last 2 bits
break;
case 1:
alph_index = c >> 4; // get last 4 bits
alph_index += tmp;
tmp = (c & 0x0f) << 2;
break;
case 2:
alph_index = tmp;
alph_index += c >> 6;
b64_output(b64_alphabet[alph_index]);
alph_index = c & 0x3f;
break;
}
b64_output(b64_alphabet[alph_index]);
spoke = (spoke + 1) % 3;
}
if (spoke == 1) {
alph_index = tmp;
b64_output(b64_alphabet[alph_index]);
b64_output('=');
b64_output('=');
} else if (spoke == 2) {
alph_index = tmp;
b64_output(b64_alphabet[alph_index]);
b64_output('=');
}
putchar('\n');
}