Convert hex values in an NSData object to NSString?

  • I'm using Andreas Mayer's NSData_AMDigest category to get an MD5
    digest. It returns an NSData object, but what I need now is an
    NSString of the hex characters.

    What's the best way to do this? Sorry, I'm an interface guy, and not
    very good at twiddling bits. Any help would be appreciated.

    --
    Dave Batton
    Mere Mortal Software
    http://www.Mere-Mortal-Software.com/blog/
  • On Nov 29, 2007, at 11:27 AM, Dave Batton wrote:

    > I'm using Andreas Mayer's NSData_AMDigest category to get an MD5
    > digest. It returns an NSData object, but what I need now is an
    > NSString of the hex characters.
    >
    > What's the best way to do this?

    -[NSData description] is one way of doing it...

    Nick Zitzmann
    <http://www.chronosnet.com/>
  • On Nov 29, 2007 12:27 PM, Dave Batton <Dave...> wrote:
    > I'm using Andreas Mayer's NSData_AMDigest category to get an MD5
    > digest. It returns an NSData object, but what I need now is an
    > NSString of the hex characters.
    >
    > What's the best way to do this? Sorry, I'm an interface guy, and not
    > very good at twiddling bits. Any help would be appreciated.

    I'd probably just write a quick category on NSData. Something like
    this would work nicely:

    #import <Foundation/Foundation.h>

    @interface NSData (NSData_HexAdditions)
    - (NSString*) stringWithHexBytes;
    @end

    @implementation NSData (NSData_HexAdditions)
    - (NSString*) stringWithHexBytes {
    NSMutableString *stringBuffer = [NSMutableString
    stringWithCapacity:([self length] * 2)];
    const unsigned char *dataBuffer = [self bytes];
    int i;

    for (i = 0; i < [self length]; ++i)
      [stringBuffer appendFormat:@"%02X", (unsigned long)dataBuffer[ i ]];

    return [[stringBuffer copy] autorelease];
    }
    @end

    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSLog( @"Hex String = %@", [[@"Here is a test!\n"
    dataUsingEncoding:NSUTF16StringEncoding] stringWithHexBytes] );

        [pool release];
        return 0;
    }
previous month november 2007 next month
MTWTFSS
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    
Go to today