【问题标题】:How can i convert hex value to NSString?如何将十六进制值转换为 NSString?
【发布时间】:2013-05-06 10:15:22
【问题描述】:

我有以下代码用于将十六进制值转换为相应的 nsstring,但它对我不起作用

NSMutableString * newString = [[NSMutableString alloc] init];
NSString *string=@"5c 57 c7 25 d9 57 b9 4c";
NSScanner *scanner = [[NSScanner alloc] initWithString:string];
unsigned value;
while([scanner scanHexInt:&value]) {
    [newString appendFormat:@"%c",(char)(value & 0xFF)];
}
string = [newString copy];
NSLog(@"%@",string);

请帮帮我

【问题讨论】:

    标签: ios nsstring hex nsmutablestring


    【解决方案1】:

    这样尝试一次,

    - (NSString *) stringFromHex:(NSString *)str 
    {   
        NSMutableData *stringData = [[NSMutableData alloc] init] ;
        unsigned char whole_byte;
        char byte_chars[3] = {'\0','\0','\0'};
        int i;
        for (i=0; i < [str length] / 2; i++) {
            byte_chars[0] = [str characterAtIndex:i*2];
            byte_chars[1] = [str characterAtIndex:i*2+1];
            whole_byte = strtol(byte_chars, NULL, 16);
            [stringData appendBytes:&whole_byte length:1]; 
        }
    
        return [[NSString alloc] initWithData:stringData encoding:NSASCIIStringEncoding] ;
    }
    

    这样打电话,

    NSString* string = [self stringFromHex:@"5c 57 c7 25 d9 57 b9 4c"];
    NSLog(@"%@",string);
    

    【讨论】:

      【解决方案2】:

      我在需要时尝试了这个尝试这个。

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

      【讨论】:

        【解决方案3】:

        您可以将其转换为:

        NSString *str=@"5c 57 c7 25 d9 57 b9 4c";
        NSMutableString * newString = [NSMutableString string];
        
        NSArray * components = [str componentsSeparatedByString:@" "];
        for ( NSString * component in components ) {
            int value = 0;
            sscanf([component cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
            [newString appendFormat:@"%c", (char)value];
        }
        
        NSLog(@"%@", newString);
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 2011-03-04
          • 2012-06-16
          • 2011-05-15
          • 2017-04-03
          • 2011-09-04
          • 2012-10-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多