lre*_*old 5 iphone hex ascii objective-c nsstring
我需要将十六进制值的NSString转换为文本的NSString(ASCII).例如,我需要这样的东西:
"68 65 78 61 64 65 63 69 6d 61 6c" to be "hexadecimal"
Run Code Online (Sandbox Code Playgroud)
我已经查看并调整了此线程中的代码,但它对我不起作用.它仅适用于一对十六进制.与空间有关?任何提示或示例代码都非常感谢.
那么我会为你的目的修改同样的东西.
NSString * str = @"68 65 78 61 64 65 63 69 6d 61 6c";
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);
Run Code Online (Sandbox Code Playgroud)
您可以使用NSScanner获取每个角色.需要空格来分隔每个值,否则扫描仪将继续扫描并忽略其他数据.
- (NSString *)hexToString:(NSString *)string {
NSMutableString * newString = [[NSMutableString alloc] init];
NSScanner *scanner = [[NSScanner alloc] initWithString:string];
unsigned value;
while([scanner scanHexInt:&value]) {
[newString appendFormat:@"%c",(char)(value & 0xFF)];
}
string = [newString copy];
[newString release];
return [string autorelease];
}
// called like:
NSLog(@"%@",[self hexToString:@"68 65 78 61 64 65 63 69 6d 61 6c"]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7333 次 |
| 最近记录: |