문제

I have following code for converting hex value to corresponding nsstring but its not working for me

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

please help me

도움이 되었습니까?

해결책

once try like this,

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

call like this ,

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

다른 팁

i Tried this when required try this.

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

You can use convert this as :

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

Hope it helps you.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top