Basic c++ help with MemoryBlock


#1

Hello

I’m trying to get the encoding function from http://www.adp-gmbh.ch/cpp/common/base64.html to encode a File, so I though the best way would be to get it to work with a MemoryBlock and i don’t quite understand why I’m getting messed up results, because I’m a noob.

The original function:

[code]static const std::string base64_chars =
“ABCDEFGHIJKLMNOPQRSTUVWXYZ”
“abcdefghijklmnopqrstuvwxyz”
“0123456789+/”;

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];

while (in_len–) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;

  for(i = 0; (i <4) ; i++)
    ret += base64_chars[char_array_4[i]];
  i = 0;
}

}

if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = ‘\0’;

char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;

for (j = 0; (j < i + 1); j++)
  ret += base64_chars[char_array_4[j]];

while((i++ < 3))
  ret += '=';

}

return ret;

}[/code]

My version:

[code]String Base64::base64_encode(MemoryBlock& mb) {
static const String base64_chars =
“ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/”;
int memoryBlockPosition = 0;
int numBytes = mb.getSize();
String ret;

int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];

while (memoryBlockPosition < numBytes)
{
	char_array_3[i++] = mb[memoryBlockPosition++];

	..... the rest is the same as above...

}[/code]

thanks for any hints! :roll:


#2

Can’t see anything obvious - you probably need to spend some quality time with your debugger. Also have a look at the MemoryBlock::toBase64Encoding() function, which uses a different format, but might be informative.


#3

i had the same exact problem, but i got it to work with the standard base64 encoding used on the net: http://code.google.com/p/ctrlr/source/browse/#svn/trunk/EdoController/Primitives (Base64.cpp and Base64.h)


#4

thanks for the links atom, i got it working now.