Reputation: 9740
I have tried googling it but didn't got the exact answer as required.
I want to convert a NSString into Byte Array in iPhone.
Also I want to know that Do the result of conversion of NSString to byteArray in iPhone will be same as conversion of string to byteArray in JAVA?
Thanks for your help in advance...
Upvotes: 3
Views: 7034
Reputation: 950
The following code may help you.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *str = @"Sample String";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger len = str.length;
uint8_t *bytes = (uint8_t *)[data bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:len * 3];
[result appendString:@"["];
int i = 0;
while(i < len){
if (i) {
[result appendString:@","];
}
[result appendFormat:@"%d", bytes[i]];
i++;
}
[result appendString:@"]"];
NSLog (@"String is %@",str);
NSLog (@"Byte array is %@",result);
[pool drain];
return 0;
}
Thanks, prodeveloper
Upvotes: 0
Reputation: 124997
There are many different encodings possible. If you use the same encoding in both Objective-C and in Java, then you should get the same bytes (or string, if you're going the other way). I'd expect Java to use UTF8, which is specified in Cocoa as NSUTF8StringEncoding
.
There are several methods in NSString for converting a string to a pile o' bytes. Three of them are: -cStringUsingEncoding:
, -UTF8String
, and -dataUsingEncoding:
. The first returns a char * pointing to a null-terminated array of char. The second does pretty much the same thing as calling the first and specifying UTF8. The third returns a NSData*, and you can access the bytes directly using NSData's -bytes
method.
Upvotes: 3
Reputation: 23169
NSData* bytes = [str dataUsingEncoding:NSUTF8StringEncoding];
Do the result of conversion of NSString to byteArray in iPhone will be same as conversion of string to byteArray in JAVA?
I believe this is standardized by UTF-8, so yes.
Upvotes: 2