0

I have a method in my app that I would like to write hex values into a file (essentially creating an image from the written bytes). I can't seem to figure out how to encode the values properly to produce the image. Any suggestion would be appreciated - thanks.

- (void)makeImage {

@autoreleasepool {

    NSString* hexValues = @"8950..." // these are the hex bytes that make up the image file

    NSString* fileName    = @"image.png";
    NSString* homeDir     = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/"];

    NSString* fullPath = [homeDir stringByAppendingPathComponent:fileName];

    NSError* error = nil;
    [lastLine writeToFile:fullPath atomically:NO encoding:NSASCIIStringEncoding error:&error];

}
Joe Habadas
  • 628
  • 8
  • 21
  • You're basic problem is that your "hexValues" object isn't -- it's a string with characters in it that look like hex values when printed. Not clear why/how you'd get the bits of an image in that form, but if that's what you have, you need to convert each pair of "hex" characters into one 8-bit byte, using one of the techniques discussed below. – Hot Licks Sep 07 '12 at 00:29

1 Answers1

0

You can convert the NSString in an NSData with lossy ASCII encoding or UTF-8, then you can use the method -[NSData bytes] to get to the raw bytes.

Use a for loop to loop through them 2 bytes at a time, you can then either copy the two bytes/characters you are upto into a char array of of size 3 (3 to include the \0, make sure you initialize it with "00" to get a terminating \0) you can then use the c function

long int strtol ( const char * str, char ** endptr, int base );

to convert the two bytes/hex to an integer.

Alternatively you can write your own hex-string to int that doesn't require a terminating \0.

Nathan Day
  • 5,981
  • 2
  • 24
  • 40
  • If you want to use a object-oriented method, NSScanner is a good approach. Also see this question: [Objective-C - Parse hex string to integer?](http://stackoverflow.com/questions/3648411/objective-c-parse-hex-string-to-integer) – Richard J. Ross III Sep 07 '12 at 00:02
  • @Nathan, hi thanks for the answer — how would i write my own hex-string to int? – Joe Habadas Sep 07 '12 at 02:26
  • covert each character into a int by using c-'0' for digits or c-'A' for uppercase. you will then have two int, one and two, to convert into a single byte value use (one<<4)+two; – Nathan Day Sep 07 '12 at 03:29