Find the number of different bits in two binary numbers

Programming: How many bits are different in the binary representation of two int (32-bit) integers m and n?

Ideas:

  1. First, perform a bitwise XOR between m and n. At this time, the same binary bit of m and n is cleared, and the different binary bit is 1.
  2. Count the number of 1s in the binary bits of the result after the XOR is completed
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int diff_bit(int m, int n)
{
    
    
	int tmp = m ^ n;
	int count = 0;
	while (tmp)
	{
    
    
		tmp = tmp & (tmp - 1);
		count++;
	}
	return count;
}
int main()
{
    
    
	int m, n;
	printf("请输入两个数字: ");
	scanf("%d %d", &m, &n);
	int ret = diff_bit(m, n);
	printf("ret=%d\n", ret);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_45658339/article/details/108590426