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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With