C语言 如何在 NSLog() 中打印 unsigned char*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13522962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:31:15  来源:igfitidea点击:

How to print unsigned char* in NSLog()

objective-cccharunsignednslog

提问by HelmiB

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.

任何的想法?提前致谢。

采纳答案by rmaddy

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

char数组没有格式说明符。一种选择是NSData从数组创建一个对象,然后记录该NSData对象。

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

回答by Stripes

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.

对于较小的数据块,您可以尝试创建一个 NSData 并使用 debugDescription 方法。目前这是一个十六进制转储,但没有什么能保证它永远是一个。

回答by fotios

To print char* in NSLog try the following:

要在 NSLog 中打印 char*,请尝试以下操作:

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

You will need to nullterminate your string.

您将需要null终止您的字符串。

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.

返回通过从给定的 UTF8 编码字节的给定 C 数组中复制字符来初始化的 NSString 对象。