开发者

How to convert HEX to NSString in Objective-C?

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 ?开发者_StackOverflow社区


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;
}


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;
}


+(NSString*)intToHexString:(NSInteger)value
{
return [[NSString alloc] initWithFormat:@"%lX", value];
}


extension String {
    func hexToString()-> String {
        var newString = ""
        var i = 0
        while i < self.count {
            let hexChar = (self as NSString).substring(with: NSRange(location: i, length: 2))
            if let byte = Int8(hexChar, radix: 16) {
                if (byte != 0) {
                    newString += String(format: "%c", byte)
                }
            }
            i += 2
        }
        return newString
    }
}


I think the people advising initWithFormat is the best answer as it's objective-C rather than a mix of ObjC, C.. (although the sample code is a bit terse).. I did the following

unsigned int resInit = 0x1013;
if (0 != resInit)
{
    NSString *s = [[NSString alloc] initWithFormat:@"Error code 0x%lX", resInit];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Initialised failed"
        message:s
        delegate:nil
        cancelButtonTitle:@"OK"
        otherButtonTitles:nil];
    [alert show];
    [alert release];
    [s release];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜