关于位运算符的一些问题

发布于 2024-10-03 08:03:34 字数 717 浏览 3 评论 0原文

我今天读到了有关按位运算符的内容,它们对我来说似乎相当方便。我还注意到 Apple 也使用它们,例如 UIViewAutoresizing。

在我的应用程序中,我需要跟踪一周中的 7 天。每一天都可以启用或禁用。我曾经有七个 BOOL,但现在我尝试使用单个整数来实现此目的:

enum {
    DaysMonday = 1 << 0,
    DaysTuesday = 1 << 1,
    DaysWednesday = 1 << 2,
    DaysThursday = 1 << 3,
    DaysFriday = 1 << 4,
    DaysSaturday = 1 << 5,
    DaysSunday = 1 << 6
};
typedef NSUInteger Days;

我的问题是,现在如何启用/禁用这些值?我知道我可以检查特定日期的变量 days ,如下所示:

if (days & DaysThursday) {
    // thursday enabled
}

但是我如何..

  1. 启用星期四?
  2. 周四禁用?
  3. 周四切换?
  4. 启用全部?
  5. 全部禁用?

谢谢。

I read about bitwise operators today and they seem rather handy to me. I also noticed Apple uses them too, for example with UIViewAutoresizing.

In my app I need to keep track of the seven days of the week. Each day can be either enabled or disabled. I used to have seven BOOL's, but now I'm trying to use a single integer for this:

enum {
    DaysMonday = 1 << 0,
    DaysTuesday = 1 << 1,
    DaysWednesday = 1 << 2,
    DaysThursday = 1 << 3,
    DaysFriday = 1 << 4,
    DaysSaturday = 1 << 5,
    DaysSunday = 1 << 6
};
typedef NSUInteger Days;

My question is, how can I enable/disable those values now? I know I can check a variable days for a specific day like this:

if (days & DaysThursday) {
    // thursday enabled
}

But how do I..

  1. enable thursday?
  2. disable thursday?
  3. toggle thursday?
  4. enable all?
  5. disable all?

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

好倦 2024-10-10 08:03:34

我对 Objective-C 不太熟悉,但这里是处理按位运算符的基础知识。

启用星期四

days = days | DaysThursday;

禁用星期四

allDays = DaysMonday | DaysTuesday | ... | DaysSunday;
days = days & (allDays ^ DaysThursday);
// OR
days = days & ~DaysThursday;

切换星期四

days = days ^ DaysThursday; 

全部启用

allDays = DaysMonday | DaysTuesday | ... | DaysSunday;
days = days | allDays;
// OR
days = allDays;

全部禁用

days = days ^ days;
// OR
days = 0;

I'm not too familiar with objective-c, but here are the basics when dealing with bitwise operators.

Enable Thursday

days = days | DaysThursday;

Disable Thursday

allDays = DaysMonday | DaysTuesday | ... | DaysSunday;
days = days & (allDays ^ DaysThursday);
// OR
days = days & ~DaysThursday;

Toggle Thursday

days = days ^ DaysThursday; 

Enable All

allDays = DaysMonday | DaysTuesday | ... | DaysSunday;
days = days | allDays;
// OR
days = allDays;

Disable All

days = days ^ days;
// OR
days = 0;
已下线请稍等 2024-10-10 08:03:34
days = DaysMonday | DaysWednesday | DaysFriday | DaysSaturday;
days = days | DaysThursday;
days = days & ~DaysSaturday;
days = DaysMonday | DaysWednesday | DaysFriday | DaysSaturday;
days = days | DaysThursday;
days = days & ~DaysSaturday;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文