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

2 Answers

0 votes
#include <stdio.h>
 
int countBits(int num1, int num2) {
    int count = 0;
    int lsb1 = 0, lsb2 = 0;
 
    while ((num1 > 0) || (num2 > 0)) {
        lsb1 = num1 & 1;
        lsb2 = num2 & 1;
 
        if (lsb1 != lsb2) {
            count++;
        }
 
        num1 = num1 >> 1;
        num2 = num2 >> 1;
    }
     
    return count;
}
 
int main()
{
    int num1 = 2;  // 00000010
    int num2 = 17; // 00010001
    printf("Number of bits to be flipped : %d\n", countBits(num1, num2));
     
    num1 = 3;   // 00000011
    num2 = 221; // 11011101
    printf("Number of bits to be flipped : %d\n", countBits(num1, num2));
     
    return 0;
}
 
 
   
   
/*
run:
 
Number of bits to be flipped : 3
Number of bits to be flipped : 6
     
*/

 



answered Dec 23, 2023 by avibootz
edited Dec 25, 2023 by avibootz
0 votes
#include <stdio.h>

int countBits(int num1, int num2) {
    int n = num1 ^ num2;
    int count = 0;
      
    while (n > 0) {
        count++;
        n &= (n - 1);
    }
    
    return count;
}

int main()
{
    int num1 = 2;  // 00000010
    int num2 = 17; // 00010001
    printf("Number of bits to be flipped : %d\n", countBits(num1, num2));
    
    num1 = 3;   // 00000011
    num2 = 221; // 11011101
    printf("Number of bits to be flipped : %d\n", countBits(num1, num2));
    
    return 0;
}


  
  
/*
run:

Number of bits to be flipped : 3
Number of bits to be flipped : 6
    
*/

 



answered Dec 23, 2023 by avibootz
...