Geek@Paris

base64 encoder decoder for objective-c (iPhone or Mac)

2010-02-24

I use base64 encoder and decoder to put binary data of images into xml data, then transfer the non-text data as text data between server and client.

Here’s an example in my iPhone project.

base64.zip

Download these two files and import them in your project and include the head file in your class file.

(Thanks to Jonathan Wight, who wrote it on Mar 18, 2003)

There are four methods in the base64 head file.

extern size_t EstimateBas64EncodedDataSize(size_t inDataSize);
extern size_t EstimateBas64DecodedDataSize(size_t inDataSize);
extern bool Base64EncodeData(const void *inInputData, size_t inInputDataSize, char *outOutputData, size_t *ioOutputDataSize, BOOL wrapped);
extern bool Base64DecodeData(const void *inInputData, size_t inInputDataSize, void *ioOutputData, size_t *ioOutputDataSize)

Here’s the usage of decoding a string data.

NSString *stringValue = /*the UTF8 string parsed from xml data*/
Byte inputData[[stringValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];//prepare a Byte[]
[[stringValue dataUsingEncoding:NSUTF8StringEncoding] getBytes:inputData];//get the pointer of the data
size_t inputDataSize = (size_t)[stringValue length];
size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);//calculate the decoded data size
Byte outputData[outputDataSize];//prepare a Byte[] for the decoded data
Base64DecodeData(inputData, inputDataSize, outputData, &outputDataSize);//decode the data
NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];//create a NSData object from the decoded data
Author:admin | Categories:Dev | Tags:

17 Comments

  1. Answer should be: Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ3JlYXQgbWVuIHRvIGNvbWUgdG8gdGhlIGFpZCBvZiB0aGVpciBjb3VudHJ5

  2. Thanks for your hard work! Always fun to try and write one from scratch! Here’s my attempt:

    char *lookup = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/”;
    NSString *stringToConvert = @”Now is the time for all great men to come to the aid of their country”;
    NSMutableString *convertedString = [NSMutableString new];
    NSMutableString *binaryString = [NSMutableString new];
    const char* stringToConvertAscii = [stringToConvert UTF8String];

    for (int i=0; i<strlen(stringToConvertAscii); i++) {
    int AsciiChar = stringToConvertAscii[i];
    char eightBitRepresentation[8];
    for (int j=0; j<8; j++) {
    eightBitRepresentation[7-j] = AsciiChar % 2 ? 0×31 : 0×30;
    AsciiChar /= 2;
    }
    [binaryString appendFormat:@"%s",eightBitRepresentation];
    }
    while ([binaryString length] % 6 != 0) {
    [binaryString appendString:@"0"];
    }
    int count = 0;
    char sixBitRepresentation[6];
    for (NSUInteger i=0; i < [binaryString length]; i++) {
    sixBitRepresentation[count++] = [binaryString characterAtIndex:i] == '1' ? 1 : 0;
    if (count==6) {
    count=0;
    int myVal=0;
    for (int k=0; k<6; k++) {
    myVal += sixBitRepresentation[k]*pow(2,5-k);
    sixBitRepresentation[k]=0;
    }
    [convertedString appendFormat:@"%c",lookup[myVal]];
    }
    }
    NSLog(@"%@",convertedString);

  3. Reece says:

    Code didn’t work for me out of the box; Mach-o id error upon compiling (implementation file thinks its an objective-c file); changed the extension from base64.m to base64.mm cleaned, and recompiled. Seems like a nice efficient library;

    • admin says:

      I think you have some Objective-C++ codes in your project? So that all the .m files should be changed to .mm :) Thanks for your comment~

  4. Doggy says:

    I like your blog!
    thanks.

  5. Alexander says:

    This is running on simulator but not on my ipad..what is the issue?

  6. Humbeto says:

    I am a newbie in iphone ios programming and your code is what I am looking for, however I haven’t been able to figure out how to encode image data. Could you please supply an example for encoding NSData *imageData = UIImageJPEGRepresentation(image, 0.5);?

  7. Shiva says:

    Hi,

    Nice post. But I am trying to convert an image to string using base64 encoding. I should not convert the image to NSData. I want to convert NSString object from UIImage object directly.

    Please help me

    Thanks
    Shiva

    • admin says:

      You can convert UIImage to NSData (check iOS API document), than convert the NSData to NSString(The convert between const void * and NSData, between char * and NSString can be found on internet, they are easy.). And finally, you can wrap all the codes into a class to input UIImage and output NSString.
      Best regards.

  8. amir says:

    hi thank again i checked it and its work great!!!!
    you made wonderful job.

    one more thing , do i need to release somthing after using your example.(exept the *theData output )
    maybe inputData or outputData?

    • admin says:

      The parameters (inInputData, outOutputData, ioOutputData) are all memory points. So if you transfer a manually allocated variable (such as [[XXX alloc] init] or created by methods which have keywords “create” or “copy”), you need to release it yourself. If you are not sure about that, you can use CMD+SHIFT+A to check your project’s memory leaks or use Xcode instruments to check about that.

  9. amir says:

    hey thanks for the help i download it ,
    but i have another problem when i use your example i got error in line :
    Base64DecodeData(inputData, inputDataSize, outputData, &outputDataSize);

    the compiler doesnt know what is &
    and when i remove this it give me warning :
    warning: passing argument 4 of ‘Base64DecodeData’ makes pointer from integer without a cast

    thanks again.

  10. amir says:

    i cant download the code
    can you send it to me

    thanks.

  11. Glenn says:

    I enjoyed reading your blog. I just read that Brits vote iPhone 8th greatest invention. I love my Iphone.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Clickcha - The One-Click Captcha