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.
You want something like this?
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.