简体   繁体   中英

Byte > NSData > NSString

example: console null , please help me.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
  @autoreleasepool {

    Byte bytes[8];
    bytes[0] = 0xFE; 
    bytes[1] = 0x03; 
    bytes[2] = 0x01; 
    bytes[3] = 0x00;
    bytes[4] = 0xB4; 
    bytes[5] = 0x18; 
    bytes[6] = 0x01; 
    bytes[7] = bytes[1] ^ bytes[2] ^ bytes[3] ^ bytes[4] ^ bytes[5] ^ bytes[6];

    NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
    NSLog(@"%@", data);

    NSString *str = [[NSString alloc] initWithBytes:&bytes length:8 encoding:NSUTF8StringEncoding];

    NSLog(@"%@", str);
  }
  return 0;
}

2016-03-10 14:48:26.566 test-byte-nsdata-nsstring[1990:1271155] 2016-03-10 14:48:26.567 test-byte-nsdata-nsstring[1990:1271155] (null) Program ended with exit code: 0

Clearly the array "bytes" doesn't contain data in UTF-8 format. For starters, 0xFE is never, ever, ever valid in a UTF-8 string. (Nor are 0xf5 to 0xff, or 0xc0 or 0xc1). But why on earth do you want to put this data into a string? It isn't a string, it's a sequence of bytes.

Use this:

NSString *str = [[NSString alloc] initWithBytes:&bytes length:8 encoding: NSASCIIStringEncoding];

Instead of this:

NSString *str = [[NSString alloc] initWithBytes:&bytes length:8 encoding: NSUTF8StringEncoding];

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