2011-11-05 25 views
3
创建字节数组

请任何一个指导我如何从NSData的字节数组,这里是我的createing代码的NSData如何从NSData的

NSData* data = UIImagePNGRepresentation(img); 
+0

尝试[这](http://stackoverflow.com/questions/ 724086/how-to-convert-nsdata-to-byte-array-in-iphone/724365#724365)我认为这会对你有所帮助 – salahy

+0

你阅读[NSData的文档](https://developer.apple.com /library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html)。其他一切都只是简单的C代码。 –

回答

3

如果你只想读他们,有一个非常简单的方法:

unsigned char *bytes = [data bytes]; 

如果你想要编辑的数据,有一个method on NSData that does this

// Make your array to hold the bytes 
NSUInteger length = [data length]; 
unsigned char *bytes = malloc(length * sizeof(unsigned char)); 

// Get the data 
[data getBytes:bytes length:length]; 

NB不要忘记 - 如果你复制数据,您还可以在某些时候调用free(bytes);)

+1

或这种方式'UInt8 * bytes =(UInt8 *)[data subdataWithRange:(NSRange){0,length}]。bytes' – Marcin

2

这里是最快的方法(但相当危险)来获得数组:

if (lengthOfBytesArray > 100 + 1) 
{ 
    unsigned char byteWithOffset100 = bytesArray[100]; 
} 

而一个:

unsigned char *bytesArray = data.bytes; 
NSUInteger lengthOfBytesArray = data.length; 

试图让字节#100,你应该检查lengthOfBytesArray像以前一样其他安全和更objc样方式:

- (NSArray*) arrayOfBytesFromData:(NSData*) data 
{ 
    if (data.length > 0) 
    { 
     NSMutableArray *array = [NSMutableArray arrayWithCapacity:data.length]; 
     NSUInteger i = 0; 

     for (i = 0; i < data.length; i++) 
     { 
      unsigned char byteFromArray = data.bytes[i]; 
      [array addObject:[NSValue valueWithBytes:&byteFromArray 
              objCType:@encode(unsigned char)]]; 
     } 

     return [NSArray arrayWithArray:array]; 
    } 

    return nil; 
} 
+0

xcode 6为我初始化'unsigned char'和一个不兼容类型为const void的表达式的错误。 ... unsigned char byteFromArray = data.bytes [i]; – johndpope