位移编码效率(即巧妙的技巧)
我正在开发一个 Objective-C 程序,我通过网络获取位字段,并且需要根据这些位设置布尔变量。
目前,我将位域表示为 int,然后使用位移位,与此类似(所有 self 属性均为 BOOL):
typedef enum {
deleteFlagIndex = 0,
uploadFlagIndex = 1,
moveFlagIndex = 2,
renameFlagIndex = 3
} PrivilegeFlagIndex;
int userFlag = 5; //for example
// this would be YES
self.delete = ((userFlag & (1 << deleteFlagIndex)) == (1 << deleteFlagIndex));
// this would be NO
self.upload = ((userFlag & (1 << uploadFlagIndex)) == (1 << uploadFlagIndex));
这有效(据我所知),但我我想知道 - 是否有一种更高效简洁的方法来使用奇特的技巧/黑客来编码所有的小事?我之所以这么问,是因为我将为很多 标志(超过 30 个)执行此操作。
我确实意识到我也可以使用这种方法:
self.move = ((userFlag & (1 << moveFlagIndex)) > 0)
...这确实减少了打字量,但我不知道是否有充分的理由不这样做。
编辑:修改为简洁而不是高效 - 我并不担心执行性能,而是担心以智能方式执行此操作的提示和最佳实践。
I'm working on a Objective-C program where I'm getting bitfields over the network, and need to set boolean variables based on those bits.
Currently I'm representing the bitfields as int
's, and then using bit shifting, similar to this (all the self properties are BOOL):
typedef enum {
deleteFlagIndex = 0,
uploadFlagIndex = 1,
moveFlagIndex = 2,
renameFlagIndex = 3
} PrivilegeFlagIndex;
int userFlag = 5; //for example
// this would be YES
self.delete = ((userFlag & (1 << deleteFlagIndex)) == (1 << deleteFlagIndex));
// this would be NO
self.upload = ((userFlag & (1 << uploadFlagIndex)) == (1 << uploadFlagIndex));
And this works (to the best of my knowledge) but I'm wondering - is there a more efficient concise way to code all the bit twiddling using a fancy trick/hack? I ask because I'll be doing this for a lot of flags (more than 30).
I did realize I could use this method this as well:
self.move = ((userFlag & (1 << moveFlagIndex)) > 0)
...which does reduce the amount of typing, but I don't know if there's a good reason to not do it that way.
Edit: Revised to say concise rather than efficient - I wasn't worried about execution performance, but rather tips and best practices for doing this in a smart way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
现在您可以直接使用
|
组合它们。通常,检查 0 就足够了:
Try:
Now you can combine them using
|
directly.Usually, it suffices to check against 0:
您可能想尝试使用位域并让编译器自行进行优化。
You may want to try to use bitfields and let the compiler do the optimization itself.