Show 例子 4

优质
小牛编辑
125浏览
2023-12-01

Objective-C语言支持的Bitwise运算符如下表所示。 假设变量A保持60,变量B保持13,则 -

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

例子 (Example)

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

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

编译并执行上述程序时,会产生以下结果 -

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