How to print unsigned char * in NSLog ()

The name pretty much says it all.

I would like to print (NOT in decimal), but in the value of char (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.

+4
source share
3 answers

There is no format specifier for the char array. One option is to create an NSData object from an array, and then insert an NSData object into it.

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

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 need to null complete the string.

From the Apple documentation:

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

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

+1
source

Nothing in standard libraries will do this, so you could write a little hex dump function, or you could use something else that prints non-discriminatory full data. Sort of:

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

For small chunks of data, you can try to create an NSData and use the debugDescription method. This is currently a hex dump, but nothing promises it will always be one.

0
source

Source: https://habr.com/ru/post/1447861/


All Articles