3

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...

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2
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.

1 Comment

As Caleb says, NSData has a method -bytes to get the data in byte array form.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.