正确地将hex转换为base64

时间:2014-11-18 12:31:01

标签: ios objective-c base64

我正在尝试通过编码十六进制字符串来获取正确的base64字符串。它适用于我使用转换器网站,但我的应用程序没有。

NSData* sentData = [combinedHexMessage dataUsingEncoding : NSUTF8StringEncoding];
NSLog (@"%@",sentData);
NSData* sentDataBase64 = [sentData base64EncodedDataWithOptions:0];
NSLog(@"%@",[NSString stringWithUTF8String:[sentDataBase64 bytes]]);

这是我的代码。 combinedHexMessage中的NSLog看起来像这样:

ffd8ffe000104a46494600010101006000600000ffdb004300020101020101020 ...

sentData

66666438 66666530 30303130 34613436 34393436 30303031 30313031 ...

sentDataBase64

ZmZkOGZmZTAwMDEwNGE0NjQ5NDYwMDAxMDEwMTAwNjAwMDYwMDAwMGZmZGIwMDQzM ...

但它应该看起来像:

/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFB ...

因为这是我在粘贴hex字符串后得到的字符串:

http://tomeko.net/online_tools/hex_to_base64.php?lang=en

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果你有一个表示图像的十六进制字符串,你只想将该十六进制字符串转换为NSData

NSString *hexadecimalString = ...
NSData *data = [hexadecimalString dataFromHexadecimalString];
self.imageView.image = [UIImage imageWithData:data];

可能在dataFromHexadecimalString类别中定义NSString,如下所示:

@implementation NSString (Hexadecimal)

- (NSData *)dataFromHexadecimalString
{
    // in case the hexadecimal string is from `NSData` description method (or `stringWithFormat`), eliminate
    // any spaces, `<` or `>` characters

    NSString *hexadecimalString = [self stringByReplacingOccurrencesOfString:@"[ <>]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [self length])];

    NSMutableData * data = [NSMutableData dataWithCapacity:[hexadecimalString length] / 2];
    for (NSInteger i = 0; i < [hexadecimalString length]; i += 2) {
        NSString *hexChar = [hexadecimalString substringWithRange: NSMakeRange(i, 2)];
        int value;
        sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
        uint8_t byte = value;
        [data appendBytes:&byte length:1];
    }

    return data;
}

@end

此过程中不需要base-64转换。