How to convert HEX to NSString in Objective-C?

后端 未结 5 1567
终归单人心
终归单人心 2020-11-27 22:06

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\"

相关标签:
5条回答
  • 2020-11-27 22:15
    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
        }
    }
    
    0 讨论(0)
  • 2020-11-27 22:28
    +(NSString*)intToHexString:(NSInteger)value
    {
    return [[NSString alloc] initWithFormat:@"%lX", value];
    }
    
    0 讨论(0)
  • 2020-11-27 22:33

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 22:38

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 22:40

    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 讨论(0)
提交回复
热议问题