How to convert an NSString to hex values

Solution 1:

The perfect and short way to convert nsstring to hexadecimal values

NSMutableString *tempHex=[[NSMutableString alloc] init];

[tempHex appendString:@"0xD2D2D2"];

unsigned colorInt = 0;

[[NSScanner scannerWithString:tempHex] scanHexInt:&colorInt];

lblAttString.backgroundColor=UIColorFromRGB(colorInt);

The macro used for this code is----

#define UIColorFromRGB(rgbValue) 
[UIColor \colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

Solution 2:

For these lines of Java

utf8 = s.getBytes(ENCODING_UTF8);
new String(decodedHexString, ENCODING_UTF8);

Objective-C equivalents would be

utf8 = [s UTF8String];
[NSString initWithUTF8String:decodedHexString];

To make an NSString with the hexadecimal representation of a character string:

NSMutableString *hex = [NSMutableString string];
while ( *utf8 ) [hex appendFormat:@"%02X" , *utf8++ & 0x00FF];

You will have to make your own decodeHex function. Just pull two characters out of the string and, if they are valid, add a byte to the result.

Solution 3:

There is a problem with your stringToHex method - it drops leading 0s, and ignores 00s. Just as a quick fix, I made the below:

+ (NSString *) stringToHex:(NSString *)str
{   
    NSUInteger len = [str length];
    unichar *chars = malloc(len * sizeof(unichar));
    [str getCharacters:chars];

    NSMutableString *hexString = [[NSMutableString alloc] init];

    for(NSUInteger i = 0; i < len; i++ )
    {
        // [hexString [NSString stringWithFormat:@"%02x", chars[i]]]; /*previous input*/
        [hexString appendFormat:@"%02x", chars[i]]; /*EDITED PER COMMENT BELOW*/
    }
    free(chars);

    return [hexString autorelease];
}