views:

1897

answers:

3

I have a long hex value stored as a NSString, something like:

c12761787e93534f6c443be73be31312cbe343816c062a278f3818cb8363c701

How do I convert it back into a binary value stored as a char*

+2  A: 

This is a little sloppy, but should get you on the right track:

NSString *hexString = @"c12761787e93534f6c443be73be31312cbe343816c062a278f3818cb8363c701";
char binChars[128]; // I'm being sloppy and just making some room
const char *hexChars = [hexString UTF8String];
NSUInteger hexLen = strlen(hexChars);
const char *nextHex = hexChars;
char *nextChar = binChars;
for (NSUInteger i = 0; i < hexLen - 1; i++)
{
 sscanf(nextHex, "%2x", nextChar);
 nextHex += 2;
 nextChar++;
}
Rob Napier
A: 

There was a thread on this (or on a very similar) hexadecimal conversion topic a couple of weeks back over on one of the Cocoa mailing lists.

I can't reasonably reproduce the full discussion here (long thread), but the message that starts off the thread is here:

http://www.cocoabuilder.com/archive/message/cocoa/2009/5/9/236391

I do wish there were a Cocoa method for this task, but (pending finding that or pending its implementation) the code (by Mr Gecko, posted at http://www.cocoabuilder.com/archive/message/cocoa/2009/5/10/236424) looks like it would work here.

Stephen Hoffman
A: 
static NSString* hexval(NSData *data) {
    NSMutableString *hex = [NSMutableString string];
    unsigned char *bytes = (unsigned char *)[data bytes];
    char temp[3];
    int i = 0;
    for (i = 0; i < [data length]; i++) {
        temp[0] = temp[1] = temp[2] = 0;
        (void)sprintf(temp, "%02x", bytes[i]);
        [hex appendString:[NSString stringWithUTF8String: temp]];
    }
    return hex;
}
Steve918