hex and ascii
hex and ascii
- Subject: hex and ascii
- From: Darin Duphorne <email@hidden>
- Date: Sat, 5 Jan 2002 13:56:21 -0600
Thanks to some of the postings here and oreillynet.com's cocoa string series,
I have been able to get as far as I have - I am trying to read a binary file
and display its contents in a textView as Hex. Ultimately, I need to then
be able to edit it and save again, but one step at a time, I suppose:
The code snippet below "works," but some of the values are represented as
"ffffff01" for example instead of just "01" (but not all of them). Any idea
why?
Also, the app blocks until all the data is read. For large files, this is
a pain. Any idea how to avoid the character-by-character loop? I have used
bsd command line hex editors that display large files almost instantaneously.
(I can't believe there's not a convertStringToHex: method or the like.)
- (IBAction)get:(id)sender
{
NSString *expandedPath;
NSFileHandle *theFile;
NSData *nd;
NSString *fileContents;
NSMutableString *myHexString=[NSMutableString string];
int index=0;
char aChar;
//read file
expandedPath=[@"~/sample.bin" stringByExpandingTildeInPath];
theFile = [NSFileHandle fileHandleForReadingAtPath:expandedPath];
nd=[theFile readDataToEndOfFile];
//retrieve data and convert to string
fileContents= [[NSString alloc] initWith
Data:nd encoding:NSASCIIStringEncoding]
;
[textField setString:fileContents];
//loop through string and create new string of hex values
for ( index=0; index < [fileContents cStringLength] ; index++)
{
aChar=[fileContents characterAtIndex:index];
[myHexString appendFormat:@"%x ",aChar];
}
//put string in textfield
[editField setStringValue:myHexString];
//cleanup
[fileContents release];
}