C-按位运算符
时间:2020-02-23 14:31:52 来源:igfitidea点击:
在本教程中,我们将学习C编程语言中的按位运算符。
以下是我们可以在C语言中使用的按位运算符。
| 操作符 | 说明 |
|---|---|
| & | 按位AND |
| | | 按位OR |
| ^ | 按位异或者,即XOR |
| << | 向左移 |
| >> | 向右移 |
不要将按位运算符应用于浮点和双精度。
按位与
仅当两个操作数均为1时,按位AND运算符&才会给出1,否则为0。
按位与的真值表。
| A | B | A & B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
在下面的示例中,我们有两个整数值1和2,我们将执行按位与运算并显示结果。
#include <stdio.h>
int main(void)
{
//declare integer and assign value
int
x = 1,
y = 2;
//bitwise AND
int result = x & y;
printf("%d & %d = %d\n", x, y, result);
return 0;
}
1 & 2 = 0
上面代码的按位与运算的计算。
1 (decimal) = 0000 0001 (binary) & 2 (decimal) = 0000 0010 (binary) ---------------------------------- 0 (decimal) = 0000 0000 (binary)
单击此处了解如何将十进制转换为二进制。
按位或者
仅当两个操作数均为0时,按位OR|才会为0,否则为1。
按位或者的真值表。
| A | B | A | B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
在下面的示例中,我们有两个整数值1和2,我们将执行按位或者运算并显示结果。
#include <stdio.h>
int main(void)
{
//declare integer and assign value
int
x = 1,
y = 2;
//bitwise OR
int result = x | y;
printf("%d | %d = %d\n", x, y, result);
return 0;
}
1 | 2 = 3
上面代码的按位或者运算的计算。
1 (decimal) = 0000 0001 (binary) | 2 (decimal) = 0000 0010 (binary) ---------------------------------- 3 (decimal) = 0000 0011 (binary)
按位异或者
按位XOR^将为1的奇数给出1,否则为0。
按位XOR的真值表。
| A | B | A ^ B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
在下面的示例中,我们有两个整数值2和7,我们将执行按位XOR运算并显示结果。
#include <stdio.h>
int main(void)
{
//declare integer and assign value
int
x = 2,
y = 7;
//bitwise XOR
int result = x ^ y;
printf("%d ^ %d = %d\n", x, y, result);
return 0;
}
2 ^ 7 = 5
上面代码的按位XOR操作的计算。
2 (decimal) = 0000 0010 (binary) ^ 7 (decimal) = 0000 0111 (binary) ---------------------------------- 5 (decimal) = 0000 0101 (binary)
左移
我们使用左移" <<"运算符将位左移。
在下面的示例中,我们有一个整数,我们将向左移1位。
#include <stdio.h>
int main(void)
{
//declare integer and assign value
int x = 4;
//shift left
int result = x << 1;
printf("Shift left x << 1 = %d\n", result);
return 0;
}
Shift left x << 1 = 8
计算方式:
4 (decimal) = 0000 0100 (binary)
---------------------------------
4 << 1 = 0000 1000 (binary)
= 8 (decimal)
右移
我们使用右移" >>"运算符将位右移。
在下面的示例中,我们有一个整数,我们将右移1个位置。
#include <stdio.h>
int main(void)
{
//declare integer and assign value
int x = 4;
//shift right
int result = x >> 1;
printf("Shift left x >> 1 = %d\n", result);
return 0;
}
Shift right x >> 1 = 2
计算方式:
4 (decimal) = 0000 0100 (binary)
---------------------------------
4 >> 1 = 0000 0010 (binary)
= 2 (decimal)

