Read two integer numbers, then count the number of bits that need to be flipped to convert a number to another number using C program.

Program:

The source code to count the number of bits to be flipped to convert a number to another number is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to count number of bits to be flipped
// to convert a number to another number
#include <stdio.h>
#include <string.h>
int countBits(int num1, int num2)
{
int cnt = 0;
int lsb1 = 0;
int lsb2 = 0;
while ((num1 > 0) || (num2 > 0)) {
lsb1 = num1 & 1;
lsb2 = num2 & 1;
if (lsb1 != lsb2)
cnt++;
num1 = num1 >> 1;
num2 = num2 >> 1;
}
return cnt;
}
int main()
{
int num1 = 0;
int num2 = 0;
printf("Enter number1: ");
scanf("%d", &num1);
printf("Enter number2: ");
scanf("%d", &num2);
printf("Number of bits flipped: %d\n", countBits(num1, num2));
return 0;
}

Output:

RUN 1:
Enter number1: 5
Enter number2: 7
Number of bits flipped: 1
RUN2:
Enter number1: 1
Enter number2: 127
Number of bits flipped: 6
RUN 3:
Enter number1: 126
Enter number2: 65535
Number of bits flipped: 10

Explanation:

In the above program, we created two functions countBits() and main(). The countBits() function is used to count the number of bits that need to be flipped to convert a number to another number.

In the main() function, we read two integer numbers from the user and called the countBits() function to count the number of bits that need to be flipped to convert a number to another number and printed the result on the console screen.

Read two integer numbers, then count the number of bits that need to be flipped to convert a number to another number using C program.

Program:The source code to count the number of bits to be flipped to convert a number to another number is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

Output:Explanation:In the above program, we created two functions

countBits()andmain(). ThecountBits()function is used to count the number of bits that need to be flipped to convert a number to another number.In the

need an explanation for this answer? contact us directly to get an explanation for this answermain()function, we read two integer numbers from the user and called thecountBits()function to count the number of bits that need to be flipped to convert a number to another number and printed the result on the console screen.