I am trying to write a program to convert a character array in to base64.
I think I'm on the right track but I'm getting stuck. Here is what I have so far.
#include <iostream>
#include <sstream>
#include <math.h>
usingnamespace std;
int main()
{
char input[] = "d2Viam9ic0BpaGVhcnRyYWRpby5jb20";
stringstream ss;
for(int i = 0; input[i] !='\0'; i++)
{
for( int j = 7; j >= 0; j-- )
{
int bit = input[i] & ( 0x01 << j );
if ( bit > 0 ) ss << 1;
else ss << 0;
}
}
return 0;
}
So basiclly, I think have a string stream containing the binary stream of the original character array. I'm not sure if this is the most elegant way to do this but it's the best I could come up with.
I don't understand stringstream all that well. I think what I need to do is extract 6 bits at a time and convert it in to an intege. Finally, convert it in to a character. I'm just not pull out 6 bits at a time and but it into an integer.
Any advice?
Incedently. I'm trying to write this with as few libraries as possible and no asm insertions.
First thought that comes to my mind is to deal with the 6-bit groupings in threes (after all, since LCM(6, 8) = 24, each group of three 8-bit characters will give you four 6-bit base-64 values).
So I would read the input in groups of 3:
1 2 3 4 5 6 7
char a, b, c;
// Store 3 characters in a, b, and c
int val1, val2, val3, val4; // Could be done with arrays, but I'm just being lazy right now
val1 = (a & 0xFC) >> 2; // First 6 bits of a
val2 = ((a & 3) << 4) | ((b & 0xF0) >> 4); // Last 2 bits of a and first 4 bits of b
val3 = ((b & 0xF) << 2) | ((c & 0xC0) >> 6); // Last 4 bits of b and first 2 bits of c
val4 = c & 0x3F; // Last 6 bits of c
If you're wondering where the "magic" hexadecimal numbers come from:
0xFC = 11111100 in binary
3 = 00000011 in binary
0xF0 = 11110000 in binary
0xF = 00001111 in binary
0xC0 = 11000000 in binary
0x3F = 00111111 in binary
.
You'll also have to deal with the case where the size of the input isn't a multiple of 3.