位运算

一、位运算概览

符号 描述 运算规则
& 两个位都为1时,结果才为1
| 两个位都为0时,结果才为0
^ 异或 两个位相同为0,相异为1
~ 取反 0变1,1变0
<< 左移 各二进位全部左移若干位,高位丢弃,低位补0
>> 右移 各二进位全部右移若干位,对无符号数,高位补0,有符号数,各编译器处理方法不一样,有的补符号位(算术右移),有的补0(逻辑右移)

二、实例

1.~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
int main()
{
int x = 9;
printf("x=%d \n", x);
printf("~x=%d \n", ~x);
return 0;
}

//结果
x=9
~x=-10

//原理
9 (base 10) = 00000000000000000000000000001001 (base 2)
--------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)

-------------------------------------------------------------------------------
如果把x的值换成-10,那么结果正好相反

上面9和-10都是用他们的补码表示的,因为在计算机中用补码来表示数字

Bitwise NOTing any number x yields -(x + 1). For example, ~-5 yields 4.

参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT

https://www.runoob.com/w3cnote/bit-operation.html