How to print unsigned char* in NSLog()

26,787

Solution 1

There is no format specifier for an char array. One option would be to create an NSData object from the array and then log the NSData object.

NSData *dataData = [NSData dataWithBytes:data length:sizeof(data)];
NSLog(@"data = %@", dataData);

Solution 2

To print char* in NSLog try the following:

char data[6] = {'H','E','L','L','0','\n'};
NSString *string = [[NSString alloc] initWithUTF8String:data];
NSLog(@"%@", string);

You will need to null terminate your string.

From Apple Documentation:

- (instancetype)initWithUTF8String:(const char *)nullTerminatedCString;

Returns an NSString object initialized by copying the characters from a given C array of UTF8-encoded bytes.

Solution 3

Nothing in the standard libraries will do it, so you could write a small hex dump function, or you could use something else that prints non-ambigious full data. Something like:

char buf[1 + 3*dataLength];
strvisx(buf, data, dataLength, VIS_WHITE|VIS_HTTPSTYLE);
NSLog(@"data=%s", buf);

For smallish chunks of data you could try to make a NSData and use the debugDescription method. That is currently a hex dump, but nothing promises it will always be one.

Share:
26,787
HelmiB
Author by

HelmiB

IOS and Android Developer. Based on Malaysia. Developing on several Games and App on both platforms

Updated on July 29, 2020

Comments

  • HelmiB
    HelmiB almost 4 years

    Title pretty much says everything.

    would like to print (NOT in decimal), but in unsigned char value (HEX). example

    unsigned char data[6] = {70,AF,80,1A, 01,7E};
    NSLog(@"?",data); //need this output : 70 AF 80 1A 01 7E
    

    Any idea? Thanks in advance.