Objective-C 位运算符

下表列出了 Objective-C 语言支持的位运算符。假设变量 A 为 60,变量 B 为 13,则:

运算符描述实例
&如果二进制与(AND)运算符在两个操作数中都存在位,则将其复制到结果中。(A & B) 将等于 12, 即 0000 1100
|二进制或(OR)运算符复制位(如果位存在于任一操作数中)。(A | B) 将等于 61, 即 0011 1101
^如果位在一个操作数中设置,而不是在两个操作数中设置,则二进制异或(XOR)运算符复制该位。(A ^ B) 将等于 49, 即 0011 0001
~二进制一补运算符是一元的,具有 "翻转" 位的效果。(~A ) 将等于 -61, 它是 2 的补码形式的 1100 0011。
<<二进制左移位运算符。左操作数值按右操作数指定的位数向左移动。A << 2 将等于 240, 即 1111 0000
>>二进制右移运算符。左操作数值按右操作数指定的位数右移。A >> 2 将等于 15, 即 0000 1111

实例

尝试以下实例以了解 Objective-C 编程语言中可用的所有位运算符:

  1. #import <Foundation/Foundation.h>
  2. int main() {
  3. unsigned int a = 60; /* 60 = 0011 1100 */
  4. unsigned int b = 13; /* 13 = 0000 1101 */
  5. int c = 0;
  6. c = a &amp; b; /* 12 = 0000 1100 */
  7. NSLog(@"Line 1 - Value of c is %d\n", c );
  8. c = a | b; /* 61 = 0011 1101 */
  9. NSLog(@"Line 2 - Value of c is %d\n", c );
  10. c = a ^ b; /* 49 = 0011 0001 */
  11. NSLog(@"Line 3 - Value of c is %d\n", c );
  12. c = ~a; /*-61 = 1100 0011 */
  13. NSLog(@"Line 4 - Value of c is %d\n", c );
  14. c = a << 2; /* 240 = 1111 0000 */
  15. NSLog(@"Line 5 - Value of c is %d\n", c );
  16. c = a >> 2; /* 15 = 0000 1111 */
  17. NSLog(@"Line 6 - Value of c is %d\n", c );
  18. }

结果如下:

  1. 2022-07-07 22:11:51.652 demo[30836] Line 1 - Value of c is 12
  2. 2022-07-07 22:11:51.652 demo[30836] Line 2 - Value of c is 61
  3. 2022-07-07 22:11:51.652 demo[30836] Line 3 - Value of c is 49
  4. 2022-07-07 22:11:51.652 demo[30836] Line 4 - Value of c is -61
  5. 2022-07-07 22:11:51.652 demo[30836] Line 5 - Value of c is 240
  6. 2022-07-07 22:11:51.652 demo[30836] Line 6 - Value of c is 15

分类导航