本文介绍了将NSInteger附加到NSMutableData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将NSInteger附加到NSMutableData. ......的所有东西

How do you append a NSInteger to NSMutableData. Something allong the lines of...

NSMutableData *myData = [[NSMutableData alloc] init];
NSInteger myInteger = 42;

[myData appendBytes:myInteger length:sizeof(myInteger)];

以便将0x0000002A附加到myData.

So that 0x0000002A will get appended to myData.

任何帮助表示赞赏.

推荐答案

传递整数的地址,而不是整数本身的地址. appendBytes:length:需要一个指向数据缓冲区的指针和该数据缓冲区的大小.在这种情况下,数据缓冲区"是整数.

Pass the address of the integer, not the integer itself. appendBytes:length: expects a pointer to a data buffer and the size of the data buffer. In this case, the "data buffer" is the integer.

[myData appendBytes:&myInteger length:sizeof(myInteger)];

但是请记住,这将使用计算机的字节序对其进行编码.如果计划将数据写入文件或通过网络发送数据,则应改用已知的字节序.例如,要从主机(您的计算机)转换为网络字节序,请使用 htonl() :

Keep in mind, though, that this will use your computer's endianness to encode it. If you plan on writing the data to a file or sending it across the network, you should use a known endianness instead. For example, to convert from host (your machine) to network endianness, use htonl():

uint32_t theInt = htonl((uint32_t)myInteger);
[myData appendBytes:&theInt length:sizeof(theInt)];

这篇关于将NSInteger附加到NSMutableData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 07:12