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
11 const int CHARS_PER_LINE
= 72;
13 _hidden
void base64_init_encodestate(base64_encodestate
* state_in
)
15 state_in
->step
= step_A
;
17 state_in
->stepcount
= 0;
20 _hidden
char base64_encode_value(char value_in
)
22 static const char* encoding
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23 if (value_in
> 63) return '=';
24 return encoding
[(int)value_in
];
27 _hidden
int base64_encode_block(const char* plaintext_in
, int length_in
,
28 char* code_out
, base64_encodestate
* state_in
)
30 const char* plainchar
= plaintext_in
;
31 const char* const plaintextend
= plaintext_in
+ length_in
;
32 char* codechar
= code_out
;
36 result
= state_in
->result
;
38 switch (state_in
->step
)
43 if (plainchar
== plaintextend
)
45 state_in
->result
= result
;
46 state_in
->step
= step_A
;
47 return codechar
- code_out
;
49 fragment
= *plainchar
++;
50 result
= (fragment
& 0x0fc) >> 2;
51 *codechar
++ = base64_encode_value(result
);
52 result
= (fragment
& 0x003) << 4;
54 if (plainchar
== plaintextend
)
56 state_in
->result
= result
;
57 state_in
->step
= step_B
;
58 return codechar
- code_out
;
60 fragment
= *plainchar
++;
61 result
|= (fragment
& 0x0f0) >> 4;
62 *codechar
++ = base64_encode_value(result
);
63 result
= (fragment
& 0x00f) << 2;
65 if (plainchar
== plaintextend
)
67 state_in
->result
= result
;
68 state_in
->step
= step_C
;
69 return codechar
- code_out
;
71 fragment
= *plainchar
++;
72 result
|= (fragment
& 0x0c0) >> 6;
73 *codechar
++ = base64_encode_value(result
);
74 result
= (fragment
& 0x03f) >> 0;
75 *codechar
++ = base64_encode_value(result
);
77 ++(state_in
->stepcount
);
78 if (state_in
->stepcount
== CHARS_PER_LINE
/4)
81 state_in
->stepcount
= 0;
85 /* control should not reach here */
86 return codechar
- code_out
;
89 _hidden
int base64_encode_blockend(char* code_out
, base64_encodestate
* state_in
)
91 char* codechar
= code_out
;
93 switch (state_in
->step
)
96 *codechar
++ = base64_encode_value(state_in
->result
);
101 *codechar
++ = base64_encode_value(state_in
->result
);
109 return codechar
- code_out
;