开发者

NSString to ByteArray and back

I am implementing an interface, which specifies writeBytes() and readBytes() on a file.

The data has to be transported as JSON.

For readBytes I do the following:

  1. NSFileHandle readDataOfLength - to read from a file
  2. NSString initWithData: encoding: - to specify a given encoding
  3. NSString getBytes:buffer
  4. put each buffer[i] into a JSON array for transport : [116,101,115,116] for example "test" as UTF-8

On the other hand writeBytes should be doing about the same:

  1. Parse the JSON array to a NSArray开发者_JS百科
  2. NSArray getObjects:buffer - the conversion up to this point is successful
  3. NSString initWithBytes:buffer length: encoding: - is not working, the return value is null
  4. NSData dataUsingEncoding:
  5. NSFileHandle writeData

Apparently NSString initWithBytes cannot handle buffers with content such as [116,101,115,116]. Is there any other way to convert a NSString into a byte array and back ?

Thanks


Have you verified that the bytes within the array are a valid UTF-8 representation of a string? (http://en.wikipedia.org/wiki/UTF-8)

If not, you'll get back nil:

#import <Foundation/Foundation.h>

int
main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    char ary[] = { 116, 101, 115, 116, 255 };

    NSString *s = [[NSString alloc] initWithBytes: ary length: 5 encoding: NSASCIIStringEncoding];
    NSString *s2 = [[NSString alloc] initWithBytes: ary length: 5 encoding: NSUTF8StringEncoding];
    NSLog(@"s: %@, s2: %@", s, s2);

    [pool release];
}

When run, this prints:

2010-01-13 14:08:23.315 a.out[50653:903] s: testÿ, s2: (null)


Are you using the NSUnicodeStringEncoding encoding ? If so, then you may have to prefix your bytes with a valid B.O.M (See NSString reference, section "Interpreting UTF-16-encoded data").

Have you made a test with the NSASCIIStringEncoding to check that your code works for simple case ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜