将NSData转换为Base-64错误

时间:2021-11-09 18:31:18

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.

我将NSString转换为字节数组。没关系,然后我将NSData转换为base64是错误的。如果“010203040506”是正确的但是数字很高(考试:@“333435363738”)是错误的。这是我的代码。请帮帮我。

In Android: ISIjJCUm and iOS: MzQ1Njc4.

在Android中:ISIjJCUm和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
}

1 个解决方案

#1


1  

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.

您的代码生成字符串MzQ1Njc4,它是字节0x33,0x34,0x35,0x36,0x37,0x38的bas64编码。这似乎是代码的意图。

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

字符串ISIjJCUm是0x64,0x22,0x23,0x24,0x25,0x26的base64编码。

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.

请注意,0x21是十进制的33。所以看起来你要么想要在iOS上将字符串解释为十进制,要么在Android上将其解释为十六进制。

#1


1  

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.

您的代码生成字符串MzQ1Njc4,它是字节0x33,0x34,0x35,0x36,0x37,0x38的bas64编码。这似乎是代码的意图。

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

字符串ISIjJCUm是0x64,0x22,0x23,0x24,0x25,0x26的base64编码。

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.

请注意,0x21是十进制的33。所以看起来你要么想要在iOS上将字符串解释为十进制,要么在Android上将其解释为十六进制。