如何在Objective-C中将HEX转换为NSString?

时间:2011-06-21 06:33:29

标签: iphone ios ipad

我有一个带有十六进制字符串的NSString,如#34; 68656C6C6F"这意味着"你好"。

现在我想将十六进制字符串转换为另一个显示" hello"的NSString对象。怎么做?

5 个答案:

答案 0 :(得分:20)

我确信有更好,更聪明的方法可以做到这一点,但这个解决方案确实有效。

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

答案 1 :(得分:3)

这应该这样做:

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

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

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

答案 4 :(得分:-1)

我认为建议initWithFormat的人是最好的答案,因为它的目标是C而不是ObjC,C的混合......(虽然示例代码有点简洁)..我做了以下

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