位移编码效率(即巧妙的技巧)

发布于 2024-11-29 11:11:00 字数 875 浏览 1 评论 0原文

我正在开发一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

意中人 2024-12-06 11:11:00

尝试:

typedef enum {
    deleteFlag = 1 << 0,
    uploadFlag = 1 << 1,
    moveFlag = 1 << 2,
    renameFlag = 1 << 3
} PrivilegeFlags;

现在您可以直接使用 | 组合它们。

通常,检查 0 就足够了:

if (userFlag & deleteFlag) {
    // delete...
}

Try:

typedef enum {
    deleteFlag = 1 << 0,
    uploadFlag = 1 << 1,
    moveFlag = 1 << 2,
    renameFlag = 1 << 3
} PrivilegeFlags;

Now you can combine them using | directly.

Usually, it suffices to check against 0:

if (userFlag & deleteFlag) {
    // delete...
}
他夏了夏天 2024-12-06 11:11:00

您可能想尝试使用位域并让编译器自行进行优化。

You may want to try to use bitfields and let the compiler do the optimization itself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文