1

I'm getting from the webservice this hexadecimal

http://www.moodpin.it/cms/listar_avatar?id=9

and trying to convert to NSData and set the UIImageView but it doesn't work

Here is my code:

NSData *dataImage =  [appDelegate hexStringToData:avatar.avatar];
[imageView setImage:[UIImage imageWithData:dataImage]];

 - (NSData *) hexStringToData:(NSString *) aString
               {
NSString *command = aString;
command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
NSMutableData *commandToSend= [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [command length]/2; i++) {
    byte_chars[0] = [command characterAtIndex:i*2];
    byte_chars[1] = [command characterAtIndex:i*2+1];
    whole_byte = strtol(byte_chars, NULL, 16);
    [commandToSend appendBytes:&whole_byte length:1];
}
NSLog(@"%@", commandToSend);
return commandToSend;
 }

1 Answers1

1

for (i=0; i < 8; i++) {

"doesn't work" is pretty vague. My first impression is that you're only looking at the first 16 bytes (two bytes per iteration), so you're obviously not going to get a chunk of data that corresponds to the input string. Seems like you should be using the length of the string to manage the for loop. Also, if the string has an odd number of characters, your code will effectively append a 0 character to the hex string.

Aside from whatever is making your code not work, you might also consider a different approach for converting. For example, you could create a 256-character lookup table that's filled with some invalid value (-1) except for the characters that correspond to hex digits, i.e. 0..9, a..f, and A..F. The values in the table at positions corresponding to those characters would have the hex digit value, so 10 at the indices of a and A, for example. That'll only work for specific single-byte character encodings like ASCII, but that may not be a serious restriction in this case. Use the lookup table to quickly find the value of each hex digit, and then use those values as the nibbles to build your bytes.

Caleb
  • 124,013
  • 19
  • 183
  • 272