关于位运算符的一些问题
我今天读到了有关按位运算符的内容,它们对我来说似乎相当方便。我还注意到 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
}
但是我如何..
- 启用星期四?
- 周四禁用?
- 周四切换?
- 启用全部?
- 全部禁用?
谢谢。
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..
- enable thursday?
- disable thursday?
- toggle thursday?
- enable all?
- disable all?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对 Objective-C 不太熟悉,但这里是处理按位运算符的基础知识。
启用星期四
禁用星期四
切换星期四
全部启用
全部禁用
I'm not too familiar with objective-c, but here are the basics when dealing with bitwise operators.
Enable Thursday
Disable Thursday
Toggle Thursday
Enable All
Disable All