I'm writing string data to a file in which the data should be written in ASCII and then essentially repeated in Unicode. The ASCII portion is working well, but the Unicode version is garbled. Attempts to explicitly create a Unicode string with CFStringCreateMutableWithExternalCharactersNoCopy fail miserably. Advice and sample code appreciated.

有帮助吗?

解决方案

You can convert a CFStringRef to CFDataRef with CFStringCreateExternalRepresentation, for example

CFStringRef s = CFSTR("abc €");
CFDataRef d = CFStringCreateExternalRepresentation(NULL, s, kCFStringEncodingUTF16BE, 0);
// d now contains the bytes 00 61 00 62 00 63 00 20 20 ac.

Or with NSString/NSData:

NSString *s = @"abc €";
NSData *d = [d dataUsingEncoding:NSUTF16BigEndianStringEncoding];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top