当从NSString到字节,然后回到NSString时,得到奇怪的字符 [英] Getting weird characters when going from NSString to bytes and then back to NSString

查看:83
本文介绍了当从NSString到字节,然后回到NSString时,得到奇怪的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSString *message = @"testing";    
NSUInteger dataLength = [message lengthOfBytesUsingEncoding:NSUnicodeStringEncoding];
void *byteData = malloc( dataLength );
NSRange range = NSMakeRange(0, [message length]);
NSUInteger actualLength = 0;
NSRange remain;
BOOL result =   [message getBytes:byteData maxLength:dataLength usedLength:&actualLength encoding:NSUnicodeStringEncoding options:0 range:range remainingRange:&remain];
NSString *decodedString = [[NSString alloc] initWithBytes:byteData length:actualLength encoding:NSUnicodeStringEncoding];

我的问题是,我期望decodedString是测试,但它看起来像汉字。我认为这可能是一个问题与null终止的数据,但似乎不应该是一个问题。

My issue is that I expect decodedString to be testing, but instead it looks like chinese characters. I thought it could be an issue with null-terminated data, but it seems that that should not be an issue.

推荐答案

您可以执行以下任一操作:

You can do any one of the following:


  • 使用指定显式字节顺序的编码(例如 NSUTF16BigEndianStringEncoding NSUTF16LittleEndianStringEncoding

通过 NSStringEncodingConversionExternalRepresentation 中的选项:参数getBytes:maxLength:usedLength:encoding:options:range:

Pass NSStringEncodingConversionExternalRepresentation to the options: parameter in getBytes:maxLength:usedLength:encoding:options:range:. This prepends a byte-order mark to the start of the data.

使用 NSData ,作为Elvis建议。

Use NSData, as Elvis suggested.

这些天,UTF-8在大多数情况下是首选的Unicode编码。

These days, UTF-8 is the preferred Unicode encoding in most cases.

这篇关于当从NSString到字节,然后回到NSString时,得到奇怪的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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