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.

HelmiB
  • 12,303
  • 5
  • 41
  • 68

3 Answers3

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);
LombaX
  • 17,265
  • 5
  • 52
  • 77
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    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. – Hot Licks Nov 23 '12 at 04:17
  • @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. – rmaddy Nov 23 '12 at 04:20
  • out of topic, but how to just print unsigned char? not an array. – HelmiB Nov 23 '12 at 04:27
  • 1
    `%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. – rmaddy Nov 23 '12 at 04:29
  • if want to print hex, use `%x` is it? – HelmiB Nov 23 '12 at 04:32
  • 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. – rmaddy Nov 23 '12 at 04:33
  • Can i store it to `NSString` by using `stringWithFormat:` and get same output ? – HelmiB Nov 23 '12 at 09:07
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.

Stripes
  • 4,161
  • 2
  • 25
  • 29
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.

fotios
  • 204
  • 4
  • 10