2012年6月5日 星期二

NSData to Hex String & Hex String to NSData

Quick Note
// open file to NSData

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];

NSData *imageData = [NSData dataWithContentsOfFile:filePath];

NSLog(@"imageData = %@", imageData);

 

// NSData to hexString

NSString *hexString = [[imageData description] stringByReplacingOccurrencesOfString:@" " withString:@""];

hexString = [hexString stringByReplacingOccurrencesOfString:@"<" withString:@""];

hexString = [hexString stringByReplacingOccurrencesOfString:@">" withString:@""];

NSLog(@"hexString = %@", hexString);

 

// hexString to NSData

NSMutableData *data = [[NSMutableData alloc] init];

unsigned char whole_byte;

char byte_chars[3] = {'\0','\0','\0'};

int i;

for (i = 0; i < ([hexString length] / 2); i++) {

    byte_chars[0] = [hexString characterAtIndex:i*2];

    byte_chars[1] = [hexString characterAtIndex:i*2+1];

    whole_byte = strtol(byte_chars, NULL, 16);

    [data appendBytes:&whole_byte length:1]; 

}

NSLog(@"data = %@", data);

沒有留言:

張貼留言