简体   繁体   English

来自NSData的Int

[英]Int from NSData

I have a NSData object with 4 bytes length. 我有一个长度为4个字节的NSData对象。 I know this 4 bytes construcuts a positive integer. 我知道这4个字节构造了一个正整数。 How should I get the int from those NSdata object? 我该如何从那些NSdata对象中获取int?

If you know the endianness matches the current system: 如果您知道endianness与当前系统匹配:

x = *(const UInt32 *)[theData bytes];

If you know the endianness is backwards, follow that with: 如果您知道字节顺序是向后的,请按照以下步骤操作:

x = Endian32_Swap( x );

If you are not sure of the source and target endianness, you should probably find another way to pass the data. 如果您不确定源和目标字节序,则应该找到另一种传递数据的方法。

int32_t value; // make unsigned if needed. 
[myData getBytes: &value];

I have found the solution here. 我在这里找到了解决方案。

char buffer[4]; 

[data getBytes:buffer length:4]; 

int dataSize = 0; 

char cBuf2[4]; 

for(int k=0;k < 4; ++k) {

 cBuf2[k] = buffer[3-k]; 

} 

memcpy(&dataSize, cBuf2, 4); 

NSLog(@"Zip stream size :%d", dataSize);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM