简体   繁体   中英

convert NSString to Byte Array

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM