2 cencoder.c - c source to a base64 encoding algorithm implementation
4 This is part of the libb64 project, and has been placed in the public domain.
5 For details, see http://sourceforge.net/projects/libb64
8 #include "b64/cencode.h"
10 void base64_init_encodestate(base64_encodestate* state_in)
12 state_in->step = step_A;
16 char base64_encode_value(char value_in)
18 static const char* encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
19 if (value_in > 63) return '=';
20 return encoding[(int)value_in];
23 int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in)
25 const char* plainchar = plaintext_in;
26 const char* const plaintextend = plaintext_in + length_in;
27 char* codechar = code_out;
31 result = state_in->result;
33 switch (state_in->step)
38 if (plainchar == plaintextend)
40 state_in->result = result;
41 state_in->step = step_A;
42 return codechar - code_out;
44 fragment = *plainchar++;
45 result = (fragment & 0x0fc) >> 2;
46 *codechar++ = base64_encode_value(result);
47 result = (fragment & 0x003) << 4;
49 if (plainchar == plaintextend)
51 state_in->result = result;
52 state_in->step = step_B;
53 return codechar - code_out;
55 fragment = *plainchar++;
56 result |= (fragment & 0x0f0) >> 4;
57 *codechar++ = base64_encode_value(result);
58 result = (fragment & 0x00f) << 2;
60 if (plainchar == plaintextend)
62 state_in->result = result;
63 state_in->step = step_C;
64 return codechar - code_out;
66 fragment = *plainchar++;
67 result |= (fragment & 0x0c0) >> 6;
68 *codechar++ = base64_encode_value(result);
69 result = (fragment & 0x03f) >> 0;
70 *codechar++ = base64_encode_value(result);
73 /* control should not reach here */
74 return codechar - code_out;
77 int base64_encode_blockend(char* code_out, base64_encodestate* state_in)
79 char* codechar = code_out;
81 switch (state_in->step)
84 *codechar++ = base64_encode_value(state_in->result);
89 *codechar++ = base64_encode_value(state_in->result);
97 return codechar - code_out;