Question
In C programming my code is encoding a stream of data into a base64 format. How can I output in the correct format? This is
In C programming my code is encoding a stream of data into a base64 format. How can I output in the correct format?
This is the current format:
Here is my code:
#include
#include
#include
static char const alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/=";
int main(int argc, char *argv[]) {
FILE* input_fd = stdin;
// If there is a FILE argument and it isn't "-", then open that file
if (argc > 1 && strcmp(argv[1], "-") != 0) {
input_fd = fopen(argv[1], "r");
}
uint8_t in[3];
uint8_t out_idx[4];
int count = 0;
while (1) {
// read three bytes
size_t bytes_read = fread(in, sizeof(uint8_t), 3, input_fd);
// If end-of-file AND no bytes to process, print newline and exit
if (bytes_read == 0 && count == 0) {
printf(" ");
break;
}
// process input using base64 algorithm
// Upper 6 bits of byte 0
out_idx[0] = in[0] >> 2;
// Lower 2 bits of byte 0, shift left and or with the upper 4 bits of byte 1
out_idx[1] = ((in[0] & 0x03u) > 4);
// Lower 4 bits of byte 1, shift left and or with upper 2 bits of byte 2
out_idx[2] = ((in[1] & 0x0Fu) > 6);
// Last 6 bits of byte 2
out_idx[3] = in[2] & 0x3Fu;
// Write four output bytes
for (size_t i = 0; i
if (i
printf("%c", alphabet[out_idx[i]]);
} else {
printf("=");
}
}
// If end-of-file, print newline and exit
if (bytes_read
printf(" ");
break;
}
// If count == 76, print a newline
count += 4;
if (count == 76) {
printf(" ");
count = 0;
}
}
if (input_fd != stdin) {
fclose(input_fd);
}
return 0;
}
Here is what the format should look like:
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started