简体   繁体   中英

How to read Hex file in cocoa

I have 1 Hex file, i want to read this file and parse it to NSString. I used this code to read hex file but it only prinf hex code in console:

 -(void)readHexfile
{
    NSData *data = [NSData dataWithContentsOfFile:@"path file"];
    NSLog(@"Patch File: %@",data);
}

Do you have any suggestions? Thanks in advance

使用stringWithContentsOfFile:encoding:error:而不是dataWithContentsOfFile将其读取为NSString。

You'd read that using a NSScanner (convert your data to a string first using [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] (assuming your text is pure ASCII or UTF-8) or read it directly using +[NSString stringWithContentsOfFile:encoding:error:] ). See also the String Programming Guide on how to use scanners .

Edit : So it seems you want to read a file with null-terminated strings. A naive and inefficient way to do that would be:

NSData *data = [NSData dataWithContentsOfFile:@"file.path"];
NSMutableArray *strings = [NSMutableArray array];
const char *rawData = [data bytes];
NSUInteger dataLength = [data length];
NSMutableData *currentString = [NSMutableData data];

for (NSUInteger i = 0; i < dataLength; i++) {
    if (rawData[i] == 0) {
       if ([currentString length] > 0) {
           [strings addObject:[[[NSString alloc] initWithData:currentString encoding:NSUTF8StringEncoding] autorelease]];
       }
       [currentString release];
       currentString = [NSMutableData data];
    } else {
       [currentString appendBytes:&rawData[i] length:1];
    }
}

// Handle the last string if it wasn't null-terminated.
if ([currentString length] > 0) {
   [strings addObject:[[[NSString alloc] initWithData:currentString encoding:NSUTF8StringEncoding] autorelease]];
}

// "strings" now is a list of strings.

There is no such a thing like a "hex file". Hex, or hexadecimal, is a numerical system that is quite suitable to display binary data in octets (8-bit bytes) in some way suitable for humans.

What you currently do is displaying the description of the NSData object onth the console in hex.

Some quick and dirty hack could be just to use the description of the NSData.

NSString *hexString = [data description];

This will create some overhead that you could strip of using string manipulation methods. There are smater ways that may require more work.

On the contrary, if you are not interested in a hex representation then use stringWithContentsOfFile to read the file directly into an NSString object. You can then apply various encodings depending on how your file is actually encoded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM