在 C 编程语言中使用位运算符交换数字
问题
如何在 C 编程语言中使用位运算符交换数字?
解决方案
编译器交换给定的数字,首先将给定的十进制数转换为二进制等价数,然后执行按位异或运算以从一个内存位置交换到另一个内存位置。
算法
START Step 1: declare two variables a and b Step 1: Enter two numbers from console Step 2: swap two numbers by using BITWISE operator a=a^b b=a^b a=a^b Step 3: Print a and b values STOP
程序
#include<stdio.h> int main(){ int a,b; printf("enter the values for a and b:"); scanf("%d%d",&a,&b); printf("value of a=%d and b=%d before swap
",a,b); a= a^b; b= a^b; a= a^b; printf("value of a=%d and b=%d after swap",a,b); return 0; }
输出
enter the values for a and b:24 56 value of a=24 and b=56 before swap value of a=56 and b=24 after swap Explanation: a=24 binary equivalent of 24 =011000 b=56 binary equivalent of 56= 111000 a= a^b = 100000 b=a^b=100000 ^ 111000 =011000 a=a^b=100000 ^ 011000 = 111000 Now a=111000 decimal equivalent =56 b= 011000 decimal equivalent = 24
广告