How to print unsigned char* in NSLog()
Asked Answered
F

3

6

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.

Forland answered 23/11, 2012 at 4:9 Comment(2)
Use printf and a for loop: #6357531Dairyman
I guess you'd have to do @"%02X %@02X %@02X ...", (unsigned int)data[0], (unsigned int)data[1], ...Sori
C
4

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);
Celeski answered 23/11, 2012 at 4:15 Comment(7)
Well, there is a format specifier for a char array -- s -- but it expects an null-terminated string and prints as ASCII characters, not hex.Sori
@HotLicks That's why I didn't mention %s because we are not dealing with a null terminated char array and the desired output is quite different from what %s provides.Celeski
out of topic, but how to just print unsigned char? not an array.Forland
%c is for unsigned char. Pull up the docs for NSString stringWithFormat:. Then click the link for "String Format Specifiers". But %c will print the character, not the hex value.Celeski
if want to print hex, use %x is it?Forland
Yes, see what @HotLicks posted in his comment to your question. %02X says to print the hex code (X) with a width of two and left padded with zeros as needed.Celeski
Can i store it to NSString by using stringWithFormat: and get same output ?Forland
M
1

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.

Mcgaha answered 23/11, 2012 at 4:18 Comment(1)
VIS_WHITE is undeclared. what to include?Forland
K
1

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.

Klong answered 29/7, 2014 at 2:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.