I need to convert an NSString of hex values into an NSString of text (ASCII). For example, I need something like:
"68 65 78 61 64 65 63 69 6d 61 6c" to be "hexadecimal"
I have looked at and tweaked the code in this thread, but it's not working for me. It is only functional with one hex pair. Something to do with the spaces? Any tips or sample code is extremely appreciated.
Well I will modify the same thing for your purpose.
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);
You can use an NSScanner to get each character. The spaces will be necessary to separate each value, or the scanner will continue scanning and ignore other data.
- (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"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With