从 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];
我的问题是,我希望解码字符串进行测试,但它看起来像汉字。我认为这可能是空终止数据的问题,但似乎这不应该是问题。
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];
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想要这样的东西吗?
You want something like this?
UTF-16 字节顺序在编码和解码之间颠倒。
您可以执行以下任一操作:
使用指定显式字节顺序的编码(例如,
NSUTF16BigEndianStringEncoding
、NSUTF16LittleEndianStringEncoding
、NSUTF8StringEncoding
)。将
NSStringEncodingConversionExternalRepresentation
传递给getBytes:maxLength:usedLength:encoding:options:range:
中的options:
参数。这会在数据的开头添加一个字节顺序标记。按照 Elvis 的建议,使用
NSData
。如今,UTF-8 是大多数情况下首选的 Unicode 编码。
The UTF-16 byte order is getting reversed between the encode and decode.
You can do any one of the following:
Use an encoding that specifies an explicit byte order (e.g.,
NSUTF16BigEndianStringEncoding
,NSUTF16LittleEndianStringEncoding
,NSUTF8StringEncoding
).Pass
NSStringEncodingConversionExternalRepresentation
to theoptions:
parameter ingetBytes:maxLength:usedLength:encoding:options:range:
. This prepends a byte-order mark to the start of the data.Use
NSData
, as Elvis suggested.These days, UTF-8 is the preferred Unicode encoding in most cases.