iOS NSData,Byte, void *, NSString的相互轉(zhuǎn)換

NSData *theData --> Byte dataByte

方式一:

theData --> NSMutableData *allData
unsigned char *dataByte = CFDataGetMutableBytePtr((__bridge CFMutableDataRef)allData); 
// unsigned char *就是Byte 的實(shí)際數(shù)據(jù)類型

方式二:
問度娘


Byte dataByte --> NSData *theData

方式一:

__block NSMutableData * dataM = [NSMutableData data];
[theData enumerateByteRangesUsingBlock:^(const void * _Nonnull bytes, NSRange byteRange, BOOL * _Nonnull stop) {

        [dataM appendBytes:bytes length:byteRange.length];
 }]; 

方式二:
問度娘


NSData *theData --> void *dataPtr

方式一:
theData --> NSMutableData *allData

void *dataPtr = allData.mutableBytes;
備注:這里不直接使用void *dataPtr = (void *)theData;
     是因?yàn)閠heData.bytes為(const Void *)類型,為了避免精度丟失盡可能使用同一數(shù)據(jù)類型

方式二:
待產(chǎn)...


void * --> NSData

查看NSData的相關(guān)文檔即可

NSData *theData --> NSString *dataStr

OC中目前這種方式最靠譜:

theData --> NSMutableData *dataM
char *pChar = (char *)dataM.mutableBytes;
char arrayChar[33];// char數(shù)組的長(zhǎng)度 = theData.length + 1,
for (int i = 0; i < theData.length; i ++) {
        
    arrayChar[i] = pChar[i];
}
arrayChar[32] = '\0';
dataStr = [NSString stringWithUTF8String:arrayChar];

NSData *theData --> int numInt

方式一:

theData --> NSMutableData *dataM
int *intArr = (int *)dataM.mutableBytes;
numInt = intArr[0];

方式二:(這種方式僅適用小端)

theData --> NSMutableData *dataM
int *intArr = (int *)dataM.mutableBytes;
int numInt = CFSwapInt32(* intArr);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容