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;
14 state_in->stepcount = 0;
17 char base64_encode_value(char value_in)
19 static const char* encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
20 if (value_in > 63) return '=';
21 return encoding[(int)value_in];
24 int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in)
26 const char* plainchar = plaintext_in;
27 const char* const plaintextend = plaintext_in + length_in;
28 char* codechar = code_out;
32 result = state_in->result;
34 switch (state_in->step)
39 if (plainchar == plaintextend)
41 state_in->result = result;
42 state_in->step = step_A;
43 return (int)(codechar - code_out);
45 fragment = *plainchar++;
46 result = (fragment & 0x0fc) >> 2;
47 *codechar++ = base64_encode_value(result);
48 result = (fragment & 0x003) << 4;
50 if (plainchar == plaintextend)
52 state_in->result = result;
53 state_in->step = step_B;
54 return (int)(codechar - code_out);
56 fragment = *plainchar++;
57 result |= (fragment & 0x0f0) >> 4;
58 *codechar++ = base64_encode_value(result);
59 result = (fragment & 0x00f) << 2;
61 if (plainchar == plaintextend)
63 state_in->result = result;
64 state_in->step = step_C;
65 return (int)(codechar - code_out);
67 fragment = *plainchar++;
68 result |= (fragment & 0x0c0) >> 6;
69 *codechar++ = base64_encode_value(result);
70 result = (fragment & 0x03f) >> 0;
71 *codechar++ = base64_encode_value(result);
73 ++(state_in->stepcount);
76 /* control should not reach here */
77 return (int)(codechar - code_out);
80 int base64_encode_blockend(char* code_out, base64_encodestate* state_in)
82 char* codechar = code_out;
84 switch (state_in->step)
87 *codechar++ = base64_encode_value(state_in->result);
92 *codechar++ = base64_encode_value(state_in->result);
100 return (int)(codechar - code_out);