# 位运算

&(按位与)、|(按位或)、^(按位异或)、~ (按位取反)。

## (1)按位与运算符(&)

`0 & 0 = 0, 0 & 1 = 0, 1 & 0 = 0, 1 & 1 = 1`

00000011
5的内部表示为
00000101

00000001

## (2)按位或运算符(|)

`0 | 0 = 0, 0 | 1 = 1, 1 | 0 = 1, 1 | 1 = 1`

j = 017|j

## (3)按位异或运算符(^)

`````` `0 ^ 0 = 0, 0 ^ 1 = 1, 1 ^ 0 = 1, 1 ^ 1 = 0 `
``````

## 移位运算

### (2)右移运算符(>>)

`printf("%d\n\n\n", -2>>4);`

```~（~0 << n） /* 实现最低n位为1，其余位为0的位串信息 */

(x >> (1+p-n)) & ~(~0 << n) /* 截取变量x自p位开始的右边n位的信息 */

new |= ((old >> row) & 1) << (15 – k) /* 截取old变量第row位，并将该位信息装配到变量new的第15-k位 */

s &= ~(1 << j) /* 将变量s的第j位置成0，其余位不变 */

for(j = 0; ((1 << j) & s) == 0; j++) ; /* 设s不等于全0，代码寻找最右边为1的位的序号j */
```

！为逻辑取反，表示非的意思

# 其他

## lowbit函数

```int lowbit(int x){
return x&(-x);
}
```

`1（0001）`
`-1（1111）`
`1&（-1）=0001`

## 判断最后一位

`x&1;` 可以取得x最后一位是1还是0

## 计算二进制中1的个数

```int bitCount(int i) {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
```

## 返回右起第一个1的位置

Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero.

```int __builtin_ffs (unsigned int x)
int __builtin_ffsl (unsigned long)
int __builtin_ffsll (unsigned long long)
```

## 返回左起第一个1之前0的个数

Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.

```int __builtin_clz (unsigned int x)
int __builtin_clzl (unsigned long)
int __builtin_clzll (unsigned long long)
```

## 返回右起第一个1之后的0的个数

Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.

```int __builtin_ctz (unsigned int x)
int __builtin_ctzl (unsigned long)
int __builtin_ctzll (unsigned long long)
```

## 返回1的个数

Returns the number of 1-bits in x.

```int __builtin_popcount (unsigned int x)
int __builtin_popcountl (unsigned long)
int __builtin_popcountll (unsigned long long)
```

## 返回1的个数的奇偶性

Returns the parity of x, i.e. the number of 1-bits in x modulo 2.

```int __builtin_parity (unsigned int x)
int __builtin_parityl (unsigned long)
int __builtin_parityll (unsigned long long)
```