我有相反的问题
如果我有:
typedef enum {
SUNDAY = (1 << 0),
MONDAY = (1 << 1),
TUESDAY = (1 << 2),
WEDNESDAY = (1 << 3),
THURSDAY = (1 << 4),
FRIDAY = (1 << 5),
SATURDAY = (1 << 6),
} PFDateDays;
我的输入是 65
例如 (SUNDAY,SATURDAY)
是否有一种巧妙的方法可以从枚举中提取这些值?
这是我的方法:
-(NSMutableArray*)selectFromMyEnum {
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
int myInput = 62;
NSArray *enumArray = @[@(SATURDAY),@(FRIDAY),@(THURSDAY),@(WEDNESDAY),@(TUESDAY),@(MONDAY),@(SUNDAY)];
for(NSNumber *numberInEnumArray in enumArray) {
if(myInput >= [numberInEnumArray integerValue]) {
[returnArray addObject:numberInEnumArray];
myInput -= [numberInEnumArray integerValue];
}
}
NSLog(@"%@",returnArray);
return returnArray;
}
这是输出:
(
64, //SATURDAY
1 //SUNDAY
)
所以这是正确的。但也许有一种我不知道的方法允许我在没有这种毫无意义的将枚举分配给数组等的情况下做到这一点。
最佳答案
我第一个想到的就是这个。由于您的枚举很好地用于标记,您可以这样做:
从您的最高枚举值 (SATURDAY) 开始,并使用按位与 (&
) 检查您的值是否包含它。然后将比较值右移 1 并重复,直到您的比较值为零。
PFDateDays comparison = SATURDAY;
//If your enum doesn't end at 1 like the above example,
//you could also use >= SUNDAY
while(((int)comparison) > 0) {
if((myVal & comparison) == comparison)
//Do what you want, this value is valid
comparison = comparison >> 1;
}
关于ios - objective-c/c++中的反向位操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18054407/