×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to count the number of bits to be flipped to convert a number to another number

Here, we are going to learn how to count the number of bits to be flipped to convert a number to another number in C programming language?
Submitted by Nidhi, on July 31, 2021

Problem statement

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.

C program to count the number of bits to be flipped to convert a number to another number

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.

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.