如何将十六进制值转换为NSString?
问题描述:
我为十六进制值转换为相应的NSString,但下面的代码它不是为我工作如何将十六进制值转换为NSString?
NSMutableString * newString = [[NSMutableString alloc] init];
NSString *[email protected]"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);
请帮我
答
一次尝试这样的,
- (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);
答
需要试试这个当我尝试这样做。
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;
}
答
你可以使用这个转换为:
NSString *[email protected]"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);
希望它可以帮助你。