什么时候sizeof(int)不是4字节在Objective-C? [英] When is sizeof(int) not 4 bytes in Objective-C?

查看:240
本文介绍了什么时候sizeof(int)不是4字节在Objective-C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用开源网络框架,使开发人员可以通过Objective-C中使用Bonjour的服务进行沟通。

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.

有一个很少有线路已经让我在边缘了一段时间,虽然他们似乎从来没有导致在我测试的任何机器的任何问题,无论我是运行32位的64位版本的我的应用程序:

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];

请注意,发送的第一条信息是数据包的长度,然后发送数据本身。令人恐惧的是长度的长度。一个机器假设int是4字节,而另一个机器认为int是8字节?

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?

如果两个尺寸在不同的机器上可能不同,会导致这个?它是依赖于我的编译器,还是终端用户的机器架构?最后,如果它是一个问题,我如何可以获取一个8字节int并将其缩小到4字节,以确保向后兼容性? (因为我永远不需要超过4个字节来表示数据包的大小。)

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 I'll never need more than 4 bytes to represent the size of the data packet.)

推荐答案

假设 sizeof(int)始终为四个字节。如果大小很重要,你应该硬编码大小为4(并编写代码将序列化值转换为具有适当字节序的四字节数组),或使用类似 int32_t < stdint.h> 中定义。

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>.

(但实际上,大多数编译器供应商决定 int 应该保留四个字节,因此您可能 不需要担心明天的一切,然后再也不是很多编译器供应商允许 int 是两个字节,当 ints 变成四个字节时,会导致许多问题,你真的应该做正确的方式,以防止未来的变化。)

(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.)

这篇关于什么时候sizeof(int)不是4字节在Objective-C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆