This program is for swapping two random bits
#include <stdio.h>
int swap_random(int num, int pos1, int pos2)
{
int value_pos1 = (num >> pos1) & 1;
int value_pos2 = (num >> pos2) & 1;
if (value_pos1 !=value_pos2)
{
num = num ^ (1 <<pos1);
num = num ^ (1 << pos2);
return num;
}
}
int main()
{
int num, pos1, pos2;
printf("\n Enter the first number : ");
scanf("%d",&num);
printf("\n Enter the first bit position :");
scanf("%d",&pos1);
printf("\n Enter the second bit position :");
scanf("%d",&pos2);
int res = swap_random(num, pos1, pos2);
printf("\n Number after swapping bit %d and bit %d is %d:\n", pos1, pos2, res);
return 0;
}
Output:
Enter the first number : 16
Enter the first bit position :4
Enter the second bit position :2
Number after swapping bit 4 and bit 2 is 4:
Categories: C Language
Leave a Reply