常量的按位或 [英] Bitwise OR of constants
问题描述
在阅读一些文件<一个href=\"http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html#//apple_ref/occ/instm/NSCalendar/components%3afromDate%3a\"相对=nofollow>这里,我碰到这个就来了:
While reading some documentation here, I came across this:
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
我不知道如何工作的。我就在C位运算符读了,但我不明白你如何适应三个(或更多!)使用一个INT内部常量,后来能以某种方式提取它们从INT回来?进一步挖掘的文件下来,我也发现了这一点,这可能与
I have no idea how this works. I read up on the bitwise operators in C, but I do not understand how you can fit three (or more!) constants inside one int and later being able to somehow extract them back from the int? Digging further down the documentation, I also found this, which is probably related:
typedef enum {
kCFCalendarUnitEra = (1 << 1),
kCFCalendarUnitYear = (1 << 2),
kCFCalendarUnitMonth = (1 << 3),
kCFCalendarUnitDay = (1 << 4),
kCFCalendarUnitHour = (1 << 5),
kCFCalendarUnitMinute = (1 << 6),
kCFCalendarUnitSecond = (1 << 7),
kCFCalendarUnitWeek = (1 << 8),
kCFCalendarUnitWeekday = (1 << 9),
kCFCalendarUnitWeekdayOrdinal = (1 << 10),
} CFCalendarUnit;
如何在(1 <<; 3;)
语句/变量的工作?我很抱歉,如果这是小事,但可能有人请解释或者或者发布一个链接到一个很好的解释?
How do the (1 << 3)
statements / variables work? I'm sorry if this is trivial, but could someone please enlighten me by either explaining or maybe posting a link to a good explanation?
推荐答案
基本上,常量重新presented只是一位,所以如果你有一个32位整数,你可以在上面安装32常数。您的常量必须是两个大国,所以他们只有一个设置位重新present。
Basically, the constants are represented just by one bit, so if you have a 32 bit integer, you can fit 32 constants in it. Your constants have to be powers of two, so they take only one "set" bit to represent.
例如:
#define CONSTANT_1 0x01 // 0001 in binary
#define CONSTANT_2 0x02 // 0010 in binary
#define CONSTANT_3 0x04 // 0100 in binary
那么你可以做
int options = CONSTANT_1 | CONSTANT_3; // will have 0101 in binary.
正如你可以看到,每一位再presents特定不变。所以,你可以二进制和在code和测试的presence每个常量,如:
As you can see, each bit represents that particular constant. So you can binary AND in your code and test for the presence of each constant, like:
if (options & CONSTANT_3)
{
// CONSTANT_3 is set
}
我建议你到约二元运算阅读(他们的工作就像逻辑运算符,但在位水平),如果你神交这个东西,它会使你一个程序员的好一点。
I recommend you to read about binary operations (they work like LOGICAL operators, but at the bit level), if you grok this stuff, it will make you a bit better of a programmer.
干杯。
这篇关于常量的按位或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!