3 回答

TA貢獻1886條經驗 獲得超2個贊
您不能使用變量聲明數組,因此Byte byteData[len];將無法使用。如果要從指針復制數據,則還需要memcpy(它將遍歷指針指向的數據并將每個字節復制到指定的長度)。
嘗試:
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
這段代碼將動態地將數組分配給正確的大?。╢ree(byteData)完成后必須提供),并將字節復制到其中。
getBytes:length:如果要使用固定長度的數組,也可以按照其他人的指示使用。這樣可以避免malloc / free,但是擴展性較差,更容易出現緩沖區溢出問題,因此我很少使用它。

TA貢獻2011條經驗 獲得超2個贊
您也可以只使用它們所在的字節,將其轉換為所需的類型。
unsigned char *bytePtr = (unsigned char *)[data bytes];

TA貢獻1835條經驗 獲得超7個贊
已經回答,但可以概括一下以幫助其他讀者:
//Here: NSData * fileData;
uint8_t * bytePtr = (uint8_t * )[fileData bytes];
// Here, For getting individual bytes from fileData, uint8_t is used.
// You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
// Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?
// Now, if you want to access whole data (fileData) as an array of uint8_t
NSInteger totalData = [fileData length] / sizeof(uint8_t);
for (int i = 0 ; i < totalData; i ++)
{
NSLog(@"data byte chunk : %x", bytePtr[i]);
}
- 3 回答
- 0 關注
- 572 瀏覽
添加回答
舉報