Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSString getBytes:maxLength:usedLength:encoding:options:range:remainingRange:

I have a string that I want as a byte array. So far I have used NSData to do this:

NSString *message = @"testing";
NSData *messageData = [message dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:YES];
NSUInteger dataLength = [messageData length];
Byte *byteData = (Byte*)malloc( dataLength );
memcpy( byteData, [messageData bytes], dataLength );

But, I know that NSString has the getBytes:maxLength:usedLength:encoding:options:range:remainingRange: method that would allow me to skip using NSData all together. My issue is, I don't know how to properly set all the parameters.

I assume the pointer array passed in has to be malloc'ed - but I'm not sure how to find how much memory to malloc. I know there is [NSString lengthOfBytesUsingEncoding:] and [NSString maximumLengthOfBytesUsingEncoding:] but I don't know if those are the methods I need to use and don't fully understand the difference between them. I assume this would be the same value given to maxLength. The rest of the parameters make sense from the documentation. Any help would be great. Thanks.

like image 247
Brian Avatar asked Nov 05 '11 10:11

Brian


1 Answers

The difference between lengthOfBytesUsingEncoding: and maximumLengthOfBytesUsingEncoding: is that the former is exact but slow (O(n)) while the latter is fast (O(1)) but may return a considerably larger number of bytes than is actually needed. The only guarantee that maximumLengthOfBytesUsingEncoding: gives is that the return value will be large enough to contain the string's bytes.

Generally, your assumptions are correct. So the method should be used like this:

NSUInteger numberOfBytes = [message lengthOfBytesUsingEncoding:NSUnicodeStringEncoding];
void *buffer = malloc(numberOfBytes);
NSUInteger usedLength = 0;
NSRange range = NSMakeRange(0, [message length]);
BOOL result = [message getBytes:buffer maxLength:numberOfBytes usedLength:&usedLength encoding:NSUnicodeStringEncoding options:0 range:range remainingRange:NULL];
...
free(buffer);
like image 91
Ole Begemann Avatar answered Oct 13 '22 22:10

Ole Begemann