0

我有以下代码用于将十六进制值转换为相应的 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);

请帮我

4

3 回答 3

1

我在需要的时候试过这个试试这个。

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;
}
于 2013-05-06T10:17:35.120 回答
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);
于 2013-05-06T10:29:34.790 回答
0

您可以将其转换为:

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

希望它可以帮助你。

于 2013-05-06T10:22:44.830 回答