Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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:

image text in transcribedHere 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:

image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Security XI Status And Prospects

Authors: T.Y. Lin, Shelly Qian

1st Edition

0412820900, 978-0412820908

More Books

Students also viewed these Databases questions

Question

6. Explain the strengths of a dialectical approach.

Answered: 1 week ago