0

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!

jopes
  • 245
  • 2
  • 13

2 Answers2

1

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
Jason Coco
  • 77,985
  • 20
  • 184
  • 180
0

For others looking for this functionality, Jason Coco's answer works really well, but has one important bug. You need to add a null character to the end of the utf8_string before returning. So just before the return statement, add the line *ep = '\0'; and that should do the trick. Also, I modified it to return an NSData object rather than an NSString, since the decoded string may use a different character encoding than UTF-8. Something like return [NSData dataWithBytes:(char *)utf8_string length:strlen(utf8_string)]; works well. Then the calling method can take care of stuffing the returned data back into an NSString using the appropriate encoding.

Community
  • 1
  • 1
SLloyd
  • 66
  • 1