Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HEX to NSString in Objective-C?

Tags:

ios

iphone

ipad

I have a NSString with hex string like "68656C6C6F" which means "hello".

Now I want to convert the hex string into another NSString object which shows "hello". How to do that ?

like image 481
user403015 Avatar asked Jun 21 '11 06:06

user403015


2 Answers

This should do it:

- (NSString *)stringFromHexString:(NSString *)hexString {

    // The hex codes should all be two characters.
    if (([hexString length] % 2) != 0)
        return nil;

    NSMutableString *string = [NSMutableString string];

    for (NSInteger i = 0; i < [hexString length]; i += 2) {

        NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSInteger decimalValue = 0;
        sscanf([hex UTF8String], "%x", &decimalValue);
        [string appendFormat:@"%c", decimalValue];
    }

    return string;
}
like image 182
Morten Fast Avatar answered Oct 15 '22 22:10

Morten Fast


I am sure there are far better, cleverer ways to do this, but this solution does actually work.

NSString * str = @"68656C6C6F";
NSMutableString * newString = [[[NSMutableString alloc] init] autorelease];
int i = 0;
while (i < [str length])
{
    NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
    int value = 0;
    sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
    [newString appendFormat:@"%c", (char)value];
    i+=2;
}
like image 26
RedBlueThing Avatar answered Oct 15 '22 21:10

RedBlueThing