Dil
Dil

Reputation: 55

How to convert NSString with hex values to Char - Objective C

I have a NSString @"460046003600430035003900" which represent hex color FF6C59.

How can i get that hex color from strings in above format:

eg: 460046003500430032003000 = FF5C20

300030004200350033004500 = 00B53E

Upvotes: 0

Views: 1638

Answers (2)

Jano
Jano

Reputation: 63707

#import <Foundation/Foundation.h>

@interface WeirdFormatDecoder : NSObject
@end

@implementation WeirdFormatDecoder

+(NSString*) decode:(NSString*)string
{
    if (!string) return @"";
    NSAssert([string length]%2==0, @"bad format");
    NSMutableString *s = [NSMutableString new];
    for (NSUInteger i=0; i<[string length]-2; i=i+2) {
        char c = [[string substringWithRange:NSMakeRange(i, 2)] integerValue];
        if (c==0) continue;
        else if (c<41){
            [s appendFormat:@"%c",[@"0123456789" characterAtIndex:c-30]];
        } else {
            [s appendFormat:@"%c",[@"ABCDEF" characterAtIndex:c-41]];
        }
    }
    return s;
}

@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSLog(@"%@",[WeirdFormatDecoder decode:@"460046003600430035003900"]); // FF6C59
        return EXIT_SUCCESS;
    }
}

Upvotes: 0

Hot Licks
Hot Licks

Reputation: 47759

Assuming that really is what you're getting, and you're not doing something to further obfuscate it, set up a loop to chop the string into 2-byte strings. Ignore every other 2-byte combo. Treat the non-ignored values as hex and convert to int, resulting in the value of an ASCII char. Do standard hex conversion on the char value to convert to a 0..15 int value. Accumulate the int values as 4 bit quantities in an int.

So you've got to do hex->int conversion twice.

Upvotes: 1

Related Questions