With reference to the following question: Convert NSData into HEX NSSString
I have solved the problem using the solution provided by Erik Aigner which is:
NSData *data = ...;
NSUInteger capacity = [data length] * 2;
NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity];
const unsigned char *dataBuffer = [data bytes];
NSInteger i;
for (i=0; i<[data length]; ++i) {
[stringBuffer appendFormat:@"%02X", (NSUInteger)dataBuffer[i]];
}
However, there is one small problem in that if there are extra zeros at the back, the string value would be different. For eg. if the hexa data is of a string @"3700000000000000", when converted using a scanner to integer:
unsigned result = 0;
NSScanner *scanner = [NSScanner scannerWithString:stringBuffer];
[scanner scanHexInt:&result];
NSLog(@"INTEGER: %u",result);
The result would be 4294967295, which is incorrect. Shouldn't it be 55 as only the hexa 37 is taken?
So how do I get rid of the zeros?
EDIT: (In response to CRD)
Hi, thanks for clarifying my doubts. So what you're doing is to actually read the 64-bit integer directly from a byte pointer right? However I have another question. How do you actually cast NSData to a byte pointer?
To make it easier for you to understand, I'll explain what I did originally.
Firstly, what I did was to display the data of the file which I have (data is in hexadecimal)
NSData *file = [NSData dataWithContentsOfFile:@"file path here"];
NSLog(@"Patch File: %@",file);
Output:
Next, what I did was to read and offset the first 8 bytes of the file and convert them into a string.
// 0-8 bytes
[file seekToFileOffset:0];
NSData *b = [file readDataOfLength:8];
NSUInteger capacity = [b length] * 2;
NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity];
const unsigned char *dataBuffer = [b bytes];
NSInteger i;
for (i=0; i<[b length]; ++i) {
[stringBuffer appendFormat:@"%02X", (NSUInteger)dataBuffer[i]];
}
NSLog(@"0-8 bytes HEXADECIMAL: %@",stringBuffer);
As you can see, 0x3700000000000000 is the next 8 bytes. The only changes I would have to make to access the next 8 bytes would be to change the value of SeekFileToOffset to 8, so as to access the next 8 bytes of data.
All in all, the solution you gave me is useful, however it would not be practical to enter the hexadecimal values manually. If formatting the bytes as a string and then parsing them is not the way to do it, then how do I access the first 8 bytes of the data directly and cast them into a byte pointer?