开发者

When is sizeof(int) not 4 bytes in Objective-C?

I'm using an open-source networking framework that makes it easy for developers to communicate over a service found using Bonjour in Objective-C.

There are a few lines that have had me on edge for a while now, even though they never seem to have caused any problems on any machines I've tested, regardless of whether I'm running the 32-bit of 64-bit version of my application:

int packetLength = [rawPacketData length];
[outgoingBuffer appendBytes:&packetLength length:sizeof(int)];
[outgoingBuffer appendData:rawPacketData];
[self writeToStream];

Note that the first piece of information sent is the length of the data packet, which is pretty standard, and then the data itself is sent. What scares me is the length of the length. Will one machine ever assume an int is 4 bytes, while the other machine believes an int to be 8 bytes?

If the two sizes could be different on different machines, what would cause this? Is it dependent on my compiler, or the end-user's machine architecture? And finally, if it is a problem, how can I take an 8-byte int and scrunch it down to 4-bytes to ensure backwards compatibility? (Since 开发者_如何学CI'll never need more than 4 bytes to represent the size of the data packet.)


You can't assume that sizeof(int) will always be four bytes. If the size matters, you should either hard-code a size of 4 (and write code to serialize values into four-byte arrays with the proper endianness), or use types like int32_t defined in <stdint.h>.

(However, as a practical matter, most compiler vendors have decided that int should stay four bytes, so you probably don't need to worry about everything breaking tomorrow. Then again, it wasn't so long ago that many compiler vendors let an int be two bytes, leading to many problems when ints became four bytes, so you really ought to do things the right way so guard against future changes.)


It could be different, but this depends on the compiler more than the machine. A different compiler might redeclare int to be 8 bytes.


Size of int depends on machine architecture; size of int will be the size of the data bus almost always, unless your C compiler does something special and changes it.

That means size of int is not 4 bytes when you compile your program in a 8-bit, 16-bit or 64-bit machine/architecture.

I would define a constant for the buffer size instead of using size of int.

Hope this answers your question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜