2011-11-05 79 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