Linux C 编程教程第 14 部分 - 位运算符实用示例
在此页
- 1。交换两个变量的值
- 2。检查数字中二进制 1 的个数
- 3。 C程序检查给定的位位置是否为1
- 结论
在我们之前的一篇文章中,我们讨论了按位运算符的基础知识。我希望您阅读了那篇文章,现在已经准备好见证和理解这些运算符的一些实际使用示例。因此,事不宜迟,让我们开始吧。
1.交换两个变量的值
我相信您知道交换两个变量值的逻辑。它涉及使用第三个变量来临时存储一个值,然后将该值分配给其中一个变量(其原始值已分配给另一个变量)。
例如,如果 a 和 b 是需要交换值的变量,而 c 是临时变量,那么标准逻辑是这样的:
c = a;
a = b;
b = c;
但是你知道整个交换过程可以通过位运算符来完成吗?是的,没错,在这种情况下,逻辑甚至不需要第三个变量。继承人的代码:
#include <stdio.h>
int main()
{
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
printf("As per your input, a = %d, and b = %d", a,b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("\nAfter swapping, a = %d, and b = %d", a,b);
return 0;
}
继承人的输出:
Enter first number: 7
Enter second number: 2
As per your input, a = 7, and b = 2
After swapping, a = 2, and b = 7
2. 检查一个数中二进制1的个数
有时您可能会发现自己处于需要计算数字中设置为 1 的位数的情况。你会很高兴知道你可以使用按位运算符轻松地做到这一点。继承人的逻辑:
#include <stdio.h>
int main()
{
int a, num_of_bits = 0;
printf("Enter a number: ");
scanf("%d", &a);
while(a)
{
if(a & 1)
num_of_bits++;
a = a >> 1;
}
printf("\nNumber of binary 1s in this number is %d", num_of_bits);
return 0;
}
继承人的输出:
Enter a number: 5
Number of binary 1s in this number is 2
3. C 程序检查给定的位位置是否为 1
有时,特别是在处理与计算机网络(协议等)相关的代码时,您需要检查特定位位置是否设置为 1。这可以使用按位运算符轻松完成。
继承人的代码:
#include <stdio.h>
int main()
{
int num, position, temp;
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter the bit position (keeping zero as base index and 31 as max): ");
scanf("%d", &position);
if(((num>>position)&1) == 1)
printf("\nBit at the position is 1");
else
printf("\nBit at the position is 0");
return 0;
}
继承人的输出:
Enter a number: 2
Enter the bit position (keeping zero as base index and 31 as max): 3
Bit at the position is 0
4.将十进制数转化为二进制形式
按位运算符也可用于将十进制数转换为二进制形式。这是一个逻辑:
#include <stdio.h>
int main()
{
int num, i = 0, temp = 0;
int bin[32] = {0}; // this will initialize all array elements to 0
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
for(i =31; i>=0; i--)
{
if((num & 1) == 1)
{
bin[i] = 1;
num = num>>1;
}
printf("The binary form of the number you entered is: ");
for(i=0; i<32; i++)
{
printf("%d",bin[i]);
}
return 0;
}
这是我案例中的输出:
Enter any number: 15
The binary form of the number you entered is: 00000000000000000000000000001111
结论
我们在此处展示的四个示例应该足以让您了解如何在实际场景中使用按位运算符。在你的机器上尝试这些,调整它们,让它们做更多的事情,或者做一些新的事情。如有任何疑问或疑问,请在此处发表评论。