Search code examples
iosobjective-cbase64nsdata

Convert NSData to Base-64 wrong


I convert NSString to byte Array. It ok, then I convert NSData to base64 is wrong. if "010203040506" is right but with high number (exam: @"333435363738") is wrong. This is my code. Please help me.

In Android: ISIjJCUm and iOS: MzQ1Njc4.

NSString *command = @"333435363738";
NSMutableData *commandToSend= [[NSMutableData alloc] init];
unsigned long whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [command length] /2; i++) {
    NSLog(@"%d",[command characterAtIndex:i*2]);
    NSLog(@"%d",[command characterAtIndex:i*2 + 1]);
    byte_chars[0] = [command characterAtIndex:i*2];
    byte_chars[1] = [command characterAtIndex:i*2 + 1];
    whole_byte = strtol(byte_chars, NULL, 16);
    [commandToSend appendBytes:&whole_byte length:1];
}



NSString *base64String;
if ([commandToSend respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
    base64String = [commandToSend base64EncodedStringWithOptions:kNilOptions];  // iOS 7+
} else {
    base64String = [commandToSend base64Encoding];                              // pre iOS7
}

Solution

  • Your code produces the string MzQ1Njc4 which is the bas64 encoding of the bytes 0x33, 0x34, 0x35, 0x36, 0x37, 0x38. This appears to be what the code is meant to do.

    The string ISIjJCUm is the base64 encoding of 0x21, 0x22, 0x23, 0x24, 0x25, 0x26.

    Note that 0x21 is 33 decimal. So it looks like you were either meant to interpret the string as decimal on iOS or as hex on Android.