Search code examples
cocoansdataextended-ascii

ASCII to NSData


This is another crack at my MD5 problem. I know the issue is with the ASCII character © (0xa9, 169). Either it is the way I am inserting the character into the string or its a higher vs lower byte problem.

If I

 NSString *source = [NSString stringWithFormat:@"%c", 0xa9];

    NSData *data = [source dataUsingEncoding:NSASCIIStringEncoding];

    NSLog(@"\n\n ############### source %@ \ndata desc %@", source, [data description]);

CC_MD5([data bytes], [data length], result);

     return [NSString stringWithFormat:
   @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
   result[0], result[1], result[2], result[3], 
   result[4], result[5], result[6], result[7],
   result[8], result[9], result[10], result[11],
   result[12], result[13], result[14], result[15]
   ];

Result:

######### source ©

[data description] = (null)
md5: d41d8cd98f00b204e9800998ecf8427e

values: int 169 char ©

When I change the encoding to

NSData *data = [NSData dataWithBytes:[source UTF8String] length:[source length]];

The result is

######### source ©

[data description] = "<"c2>
md5: 6465dad1d31752be3f3283e8f70feef7

When I change the encoding to

NSData *data = [NSData dataWithBytes:[source UTF8String] length:[source lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];

The result is ############### source © len 2 [data description] = "<"c2a9>
md5: a541ecda3d4c67f1151cad5075633423

When I run the same function in Java I get

">>>>> msg## \251 \251
md5 a252c2c85a9e7756d5ba5da9949d57ed

The question is what is the best way to get the same byte in objC as I get in Java?


Solution

  • Thanks to GBegan's explanation in another post I was able to cobble this together.

    for(int c = 0; c < [s length]; c++){
        int number = [s characterAtIndex:c];
        unsigned char c[1];
        c[0] = (unsigned char)number;
        NSMutableData *oneByte = [NSMutableData dataWithBytes:&c length:1];
    

    }