我有以下代码将十六进制值转换为相应的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);
请帮帮我
答案 0 :(得分: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;
}
答案 1 :(得分: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 :(得分: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);
希望它对你有所帮助。