Search code examples
phpobjective-ccocoastringcontent-encoding

Can you translate php function quoted_printable_decode() to an NSString-based, objective-C function / category method?


In http://php.net/quoted_printable_decode, I found ways to do it using preg_replace. Anyone who knows any code that could convert a normal NSString to something RFC 2045 section 6.7?

Thanks in advance!


Solution

  • There's no method on Cocoa to decode a quoted printable string, but you could easily write something yourself, like:

    @interface NSString (QuotedPrintableStrings)
    +(NSString*)stringWithQuotedPrintableString:(const char *)qpString;
    @end
    
    @implementation NSString (QuotedPrintableStrings)
    
    +(NSString*)stringWithQuotedPrintableString:(const char *)qpString
    {
        const char *p = qpString;
        char *ep, *utf8_string = malloc(strlen(qpString) * sizeof(char));
        NSParameterAssert( utf8_string );
        ep = utf8_string;
    
        while( *p ) {
            switch( *p ) {
                case '=':
                    NSAssert1( *(p + 1) != 0 && *(p + 2) != 0, @"Malformed QP String: %s", qpString);
                    if( *(p + 1) != '\r' ) {
                        int i, byte[2];
                        for( i = 0; i < 2; i++ ) {
                            byte[i] = *(p + i + 1);
                            if( isdigit(byte[i]) )
                                byte[i] -= 0x30;
                            else
                                byte[i] -= 0x37;
                            NSAssert( byte[i] >= 0 && byte[i] < 16, @"bad encoded character");
                        }
                        *(ep++) = (char) (byte[0] << 4) | byte[1];
                    }
                    p += 3;
                    continue;
                default:
                    *(ep++) = *(p++);
                    continue;
            }
        }
        return [[[NSString alloc] initWithBytesNoCopy:utf8_string length:strlen(utf8_string) encoding:NSUTF8StringEncoding freeWhenDone:YES] autorelease];
    }
    
    @end