C program to print bits that need to be flipped to convert a number to another number

Here, we are going to learn how to print bits that need to be flipped to convert a number to another number using C program?
Submitted by Nidhi, on July 31, 2021

Problem statement

Read two integer numbers, and then print the bits that need to be flipped to convert a number to another number.

print bits that need to be flipped to convert a number to another number in C

The source code to print bits that need 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 print bits that need to be flipped
// to convert a number to another number

#include <stdio.h>
#include <string.h>

void changedBits(int num1, int num2)
{
    int lsb1 = 0;
    int lsb2 = 0;
    int bitNum = 0;

    printf("Bits needs to be changed are:\n");
    while ((num1 > 0) || (num2 > 0)) {
        lsb1 = num1 & 1;
        lsb2 = num2 & 1;

        if (lsb1 != lsb2)
            printf("%d ", bitNum);

        num1 = num1 >> 1;
        num2 = num2 >> 1;

        bitNum++;
    }

    printf("\n");
}

int main()
{
    int num1 = 0;
    int num2 = 0;

    printf("Enter number1: ");
    scanf("%d", &num1);

    printf("Enter number2: ");
    scanf("%d", &num2);

    changedBits(num1, num2);

    return 0;
}

Output

RUN 1:
Enter number1: 5
Enter number2: 7
Bits needs to be changed are:
1 

RUN2:
Enter number1: 1
Enter number2: 127
Bits needs to be changed are:
1 2 3 4 5 6 

RUN 3:
Enter number1: 126
Enter number2: 65535
Bits needs to be changed are:
0 7 8 9 10 11 12 13 14 15 

Explanation

In the above program, we created two functions changedBits() and main(). The changedBits() function is used to print the bits, that are needed 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 changedBits() function to print the bits, that are needed to be flipped to convert a number to another number on the console screen.

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





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