Monday, August 15, 2011

Convert NSData bytes to hexadecimal in Objective-C

If you use Objective-C much, you'll most likely end up using the NSData object, and probably quite a bit. From the docs, NSData is a class for storing a byte array, something you'll likely have to do at some point if you right any amount of code.

I had some code that needed to convert the bytes in an NSData object to a hexadecimal string, so I built the following function NSDataToHex() to do this.

One thing to note about the below code is that we actually have to declare and implement an Objective-C class. This is not relevant to the conversion function, it's just the way you typically use Objective-C. The interface definition for the HexTest class is declared between the @interface and @end declaration. The actual implemented code for the class comes between @implementation and @end. Please read the comments in the main() function, as it demonstrates how to allocate the HexTest object and execute the function with parameters.

#import <Foundation/Foundation.h>

// Define the object here:
@interface HexTest : NSObject
-(NSString*) NSDataToHex:(NSData*)data;
@end

// Implement it here:
@implementation HexTest

-(NSString*) NSDataToHex:(NSData*)data
{
    const unsigned char *dbytes = [data bytes];
    NSMutableString *hexStr =
       [NSMutableString stringWithCapacity:[data length]*2];
    int i;
    for (i = 0; i < [data length]; i++) {
        [hexStr appendFormat:@"%02x ", dbytes[i]];
    }
    return [NSString stringWithString: hexStr];
}
@end

// Execute it here:
int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // (1) We must create our HexTest object first
    HexTest *hexer = [[HexTest alloc] init];
	
    // (2) Now, create a string
    NSString *str = @"helowrld";

    // (3) Make the string into NSData object
    NSData *strAsData = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    // (4) Execute our converter function
    NSLog([hexer NSDataToHex: strAsData]);

    [pool drain];
    return 0;
}

The NSDataToHex() function above basically creates an unsigned char array receiver, dbytes, and populates it by calling the bytes() function of the data object. Once the bytes are stored in this array, you can easily convert each char in the array to a hex string string using the %02x format code and append it to the string result.

Compile with

gcc `gnustep-config --objc-flags` -lgnustep-base nshex.m -o nshex

And you'll get the following results:

ok ./nshex 
2011-08-12 17:26:36.979 nshex[3773] 68 65 6c 6f 77 72 6c 64 

You can confirm the hex string is correct using an online hex converter like http://www.string-functions.com/hex-string.aspx

No comments:

Post a Comment