C language [bit operation] find the number of different bits in two numbers in binary

Find the number of different bits in two binary numbers.
Problem description:
  How many bits are different in the binary representation of two int (32-bit) integers m and n.
  Input example: 1999 2299
  Output example: 7
Programming ideas:
1. First, perform a bitwise XOR of m and n (the same bit is 0, and different bits are ORed), and after the bitwise XOR, m and n are the same binary bits The bit is cleared, and the different binary bits are 1;
2. Count the number of 1s in the binary bits   of the result (redefined temp) after the exclusive OR is completed (using bitwise AND).
code show as below:

#include<stdio.h>
int cala_diff_bit(int m, int n)//Pointer variables as function parameters
{ int tmp = m ^ n; int count = 0; while (tmp) { tmp = tmp & (tmp-1) ; count++; } return count; } int main() { int m, n; printf("Please enter two numbers: "); scanf("%d %d", &m, &n); int ret = calc_diff_bit(m , n); printf("ret=%d\n", ret); return 0; } _It's over, remember to like it if you pass by!



















Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/109792391