如何检查NSString编码

时间:2017-09-01 04:01:21

标签: ios objective-c macos unicode nsstring

我使用

读取证书信息
NSString *summary = CFBridgingRelease(SecCertificateCopySubjectSummary(cert));

获取证书摘要,当摘要为中文时,例如,摘要返回为ä¸

如何将ä¸编码为更正?

代码如何获得证书摘要

CFMutableDictionaryRef query = CFDictionaryCreateMutable(nil, 4, nil, nil);
CFDictionaryAddValue(query, kSecClass, kSecClassCertificate);

CFDictionaryAddValue(query, kSecMatchLimit, (const void *)@(100));
CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);

CFArrayRef items;
OSStatus status = SecItemCopyMatching(query, (CFTypeRef *)&items);
NSArray *certificates = CFBridgingRelease(items);
for (int i = 0; i < certificates.count; i++)
{
    SecCertificateRef certificate = (__bridge SecCertificateRef)certificates[i];
    NSString *summary = (NSString *)CFBridgingRelease(SecCertificateCopySubjectSummary(certificate);
    NSLog(@"%@", summary);
}

当summary是中文字符串时,结果不正确。

1 个答案:

答案 0 :(得分:0)

解决问题。 首先,我打印nsstring中的每个字符,看起来像

228 184 173

汉字在utf8中使用3个字符,所以我将它切换到bin

0b1110 0100
0b10 111000
0b10 101101
//for utf8 to unicode, it's
0100111000101101
//to int
20013
//which is 中 at unicode

对于UTF8 Decoding with NSString帮助,最后将字符串形式utf8切换为unicode。