ZionKing
ZionKing

Reputation: 326

obtaining NSData in hex format

I have a function returning me NSData with hex inside: eg:

NSData *temp = <000b4631 32202835 2047487a 2901088c 129824b0 48606c03 01a1070a >

Now these are hex values and I need to print them out.

x = 00
y = 0b 
z = 46 31

The ideal way to get them would be to convert them into a char array, as then I can map/typecast some structures to the array and read out what I want. How would I convert this NSData to a char array ?

Any other recommendations/best practices ?

Upvotes: 1

Views: 788

Answers (1)

Colin Wheeler
Colin Wheeler

Reputation: 3343

I have a category on NSData that does this https://github.com/Machx/Zangetsu/blob/master/Source/NSDataAdditions.m

-(NSString *)cw_hexString {
    NSUInteger capacity = [self length] * 2;
    NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity];
    const unsigned char *dataBuffer = [self bytes];

    for (NSUInteger i = 0; i < [self length]; ++i) {
        [stringBuffer appendFormat:@"%02X ",(NSUInteger)dataBuffer[i]];
    }
    if (stringBuffer) {
        return stringBuffer;
    }
    return nil;
}

Upvotes: 2

Related Questions