OC中的位运算和C/C++里的是一样的,&(按位与),| (按位或),~ (按位取反),<<(左移) ,>>(右移),^(异或)以及 &= (按位与然后赋值),|= (按位或然后赋值)等
typedef NS_OPTIONS(NSInteger, MonthType) {
//bitmask (位掩码):1111
MonthJanuary = 1 << 0, // 0001 '<<'左移运算
MonthFebruary = 1 << 1, // 0010
MonthMarch = 1 << 2, // 0100
MonthApril = 1 << 3, // 1000
};
MonthType monthType = MonthJanuary | MonthFebruary;
//添加三月
monthType |= MonthMarch; ////对应的进行按位或运算seasonType = 0011 | 1000 = 1011 等同于 monthType = monthType | MonthMarch
//把三月去掉
monthType &= ~ MonthMarch; ////对应的运算为 seasonType = 1011 & (~1000) = 1011 & 0111 = 0011; 等同于 monthType = monthType & ~ MonthMarch;
& 与运算相同为 0 相异为 1
异或运算,相同为 0 相异为 1
//定义a, b
int a = 1, b = 2;
// a = 0001 , b = 0010
a = a ^ b; // a = 0001 ^ 0010 = 0011
b = a ^ b; // b = 0011 ^ 0010 = 0001
a = a ^ b; // a = 0011 ^ 0001 = 0010
//简写的话是这样
//a ^= b;
//b ^= a;
//a ^= b;
//即 a = a ^ b 等价于 a ^= b