将 NSData 转换为字符串? [英] Convert NSData to String?

查看:31
本文介绍了将 NSData 转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 openssl 私钥 EVP_PKEY 存储为 nsdata.为此,我使用下面的代码将其序列化为字节流

I am storing a openssl private Key EVP_PKEY as nsdata. For this I am serializing into a byte stream using the code below

unsigned char *buf, *p;
int len;
len = i2d_PrivateKey(pkey, NULL);
buf = OPENSSL_malloc(len); 
p = buf;
i2d_PrivateKey(pkey, &p);

其中 pkey 的类型为 EVP_PKEY.然后我使用下面给出的行将缓冲区p"中的字节存储为 NSData

where pkey is of type EVP_PKEY. Then I am storing the bytes from buffer 'p' as an NSData using the line given below

NSData *keydata = [NSData dataWithBytes:P length:len];

现在我使用下面给出的代码将它转换为 NSString,但是当我将它打印到控制台时,它给出了一些其他字符.

Now I am converting it to a NSString using the code given below but when i print it into console its giving some other characters.

NSString *content =[ NSString stringWithCString:[keydata bytes] encoding:NSUTF8StringEncoding];

有人可以帮忙吗?

基本上我想存储 EVP_PKEY进入sqlite数据库

Basically I want to store the EVP_PKEY into a sqlite database

我在正确的轨道上吗?谢谢.

am I on the right track? Thanks.

推荐答案

Objective-C

您可以使用(参见NSString 类参考)

- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

示例:

NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];

备注:请注意 NSData 值必须对指定的编码(上例中的 UTF-8)有效,否则 nil将被退回:

Remark: Please notice the NSData value must be valid for the encoding specified (UTF-8 in the example above), otherwise nil will be returned:

如果由于某种原因初始化失败(例如如果数据没有表示用于编码的有效数据).

之前的 Swift 3.0

String(data: yourData, encoding: NSUTF8StringEncoding)

Swift 3.0 以后

String(data: yourData, encoding: .utf8)

请参阅String#init(data:encoding:) 参考

这篇关于将 NSData 转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆