简体   繁体   English

将NSInteger附加到NSMutableData

[英]Append NSInteger to NSMutableData

How do you append a NSInteger to NSMutableData. 如何将NSInteger附加到NSMutableData。 Something allong the lines of... 有些东西......

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

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

So that 0x0000002A will get appended to myData. 这样0x0000002A就会附加到myData。

Any help appreciated. 任何帮助赞赏。

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. appendBytes:length:期望指向数据缓冲区的指针和数据缓冲区的大小。 In this case, the "data buffer" is the integer. 在这种情况下,“数据缓冲区”是整数。

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

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() : 例如,要从主机(您的机器)转换为网络字节序,请使用htonl()

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

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

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