[英]How do you convert NSData to NSString or char?
I have an NSData instance containing <7e0006b5 01012605 06070172 7a>, how can I convert it to an NSString containing @"7e0006b501012605060701727a"? 我有一个包含<7e0006b5 01012605 06070172 7a>的NSData实例,如何将其转换为包含@“ 7e0006b501012605060701727a”的NSString?
My test code is: 我的测试代码是:
char c_command[26] = {'7', 'e', '0', '0',
'0', '6', 'b', '5',
'0', '1', '0', '1',
'2', '6', '0', '5',
'0', '6', '0', '7',
'0', '1', '7', '2',
'7', 'a'};
NSMutableData *commandToSend = [[NSMutableData alloc] init];
for (int i = 0; i < 13; i++) {
unsigned char data_byte;
char byte_chars[3] = {'\0','\0','\0'};
byte_chars[0] = c_command[i * 2];
byte_chars[1] = c_command[i * 2 + 1];
data_byte = strtol(byte_chars, NULL, 16);
[commandToSend appendBytes:&data_byte length:1];
}
NSString *str = [[NSString alloc] initWithData:commandToSend encoding:NSASCIIStringEncoding];
NSLog(@"Test command is :%@ \n command to string is:%@", commandToSend, str);
the output of log is: 日志的输出是:
Test command is :<7e0006b5 01012605 06070172 7a> command to string is:~
NSString *theString =[[NSString alloc]initWithData:data encoding:NSStringEncodingConversionAllowLossy];
NSLog(@"%@",theString);
[theString release];
如果数据是从Internet下载的,则可能要使用:
NSString *str = [[NSString alloc] initWithData:NSData encoding:NSASCIIStringEncoding];
NSString has a number of methods for creating strings from bytes, but you'll need to know how the data is encoded. NSString有很多从字节创建字符串的方法,但是您需要知道如何对数据进行编码。 UTF8 is a popular encoding, and if your data is UTF8 encoded you can:
UTF8是一种流行的编码,如果您的数据是UTF8编码的,则可以:
NSString *someString = [NSString stringWithUTF8String:(const char *)[someData bytes]];
There are other methods as well, such as -initWithCharacters:length:
and -initWithBytes:length:encoding:
. 还有其他方法,例如
-initWithCharacters:length:
和-initWithBytes:length:encoding:
Start by looking at the reference page for NSString . 首先查看NSString的参考页 。
I have found out that sometimes the method -stringWithUTF8String:(const char*)
from NSString
doesn't work too good in conjunction with NSData or NSMutableData. 我发现有时
NSString
-stringWithUTF8String:(const char*)
方法与NSData或NSMutableData结合使用效果不佳。 Let's have something like 让我们有这样的事情
const char * cString = [yourNSData bytes];
and 和
NSString * str = [NSString stringWithUTF8String:(const char*)cString];
Occasionally the str
was simply nil
because the cString
was somehow "malformed" (considering UTF-8 chars). 有时候,
str
只是nil
因为cString
某种程度上是“格式错误的”(考虑到UTF-8字符)。
Thus, I would recommend using 因此,我建议使用
NSString * str = [[NSString alloc] initWithData:[yourNSData bytes] encoding:NSUTF8StringEncoding];
which worked allways perfect in my case. 在我看来,这一切都非常完美。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.