转载:https://www.jianshu.com/p/b868b30c0c88
OC中的位运算和C/C++语言的位运算是一样的。一般有 &(按位与),| (按位或),~ (按位取反),<<(左移) ,>>(右移),^(异或)以及 &= (按位与然后赋值),|= (按位或然后赋值)等
对枚举类型的操作中常常会见到。
例如定义一个季节SeasonType的枚举,有春夏秋冬四个值。
1typedef NS_OPTIONS(NSInteger, SeasonType) { 2 //bitmask (位掩码):1111 3 SeasonSpring = 1 << 0, //春天 0001 '<<'左移运算 4 SeasonSummer = 1 << 1, //夏天 0010 5 SeasomAutumn = 1 << 2, //秋天 0100 6 SeasonWinter = 1 << 3, //冬天 1000 7};
你可以执行下面的操作
1//定义一个SeasonType表示春夏两个季节 2SeasonType seasonType = SeasonSpring | SeasonSummer; 3//对应的进行按位或运算seasonType = 0001 | 0010 = 0011 4 5//添加冬季 6seasonType = seasonType | SeasonWinter; 7或者 8seasonType |= SeasonWinter; 9//对应的进行按位或运算seasonType = 0011 | 1000 = 1011 10//此时seasonType同时表示了三种枚举分别是春、夏、冬 11 12//如果再把冬季去掉可以这样 13seasonType = seasonType & ~SeasonWinter; 14或者 15seasonType &= ~SeasonWinter; 16//对应的运算为 seasonType = 1011 & (~1000) = 1011 & 0111 = 0011; 17//此时seasonType又只表示了春夏两个季节。
位运符之间的优先级顺序(从高到低)为:
11 ~ 22 <<、>> 33 & 44 ^ 55 | 66 &=、^=、|=、<<=、>>=
关于异或运算我想到一个题
如何不借助第三个变量(中间变量),来交换两个数的值
此时就可以用位运算中的异或(按位对比,相同取0,不同取1)来解决
1//定义a, b 2int a = 1, b = 2; 3// a = 0001 , b = 0010 4//经过三步就可以交换a,b的值 5a = a ^ b; // a = 0001 ^ 0010 = 0011 6b = a ^ b; // b = 0011 ^ 0010 = 0001 7a = a ^ b; // a = 0011 ^ 0001 = 0010 8//交换成功 9//简写的话是这样 10//a ^= b; 11//b ^= a; 12//a ^= b; 13//即a = a ^ b 等价于a ^= b