Reputation: 23
I'm trying to get the correct base64 string by encoding a hex string. It works when I use converter websited but my App does not.
NSData* sentData = [combinedHexMessage dataUsingEncoding : NSUTF8StringEncoding];
NSLog (@"%@",sentData);
NSData* sentDataBase64 = [sentData base64EncodedDataWithOptions:0];
NSLog(@"%@",[NSString stringWithUTF8String:[sentDataBase64 bytes]]);
This is my code. combinedHexMessage
looks like this in NSLog
:
ffd8ffe000104a46494600010101006000600000ffdb004300020101020101020 ...
sentData
:
66666438 66666530 30303130 34613436 34393436 30303031 30313031 ...
sentDataBase64
:
ZmZkOGZmZTAwMDEwNGE0NjQ5NDYwMDAxMDEwMTAwNjAwMDYwMDAwMGZmZGIwMDQzM ...
But it should look like:
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFB ...
Because this is the string I get after I paste my hex
string there:
http://tomeko.net/online_tools/hex_to_base64.php?lang=en
What am I doing wrong?
Upvotes: 2
Views: 1582
Reputation: 437917
If you have a hex string that represents an image, you simply want to convert that hex string to a NSData
NSString *hexadecimalString = ...
NSData *data = [hexadecimalString dataFromHexadecimalString];
self.imageView.image = [UIImage imageWithData:data];
Where dataFromHexadecimalString
might be defined in a NSString
category like so:
@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
No base-64 conversion is needed in this process.
Upvotes: 1