The Hamming distance between two binary numbers is defined as the number of bit
ID: 3813494 • Letter: T
Question
The Hamming distance between two binary numbers is defined as the number of bit positions in which they differ. For example, the Hamming distance between two 4-bit numbers 0101 and 1100 is 2, because they differ in their first and last bits. Write a C function that takes two 32-bit inputs and returns a result of 1 if their Hamming distance is less than or equal to 1, and 0 otherwise. The function should use as few arithmetic and logic operations as possible, and should not use any loops (for, while, repeat, etc.). int hamming_distance (unsigned int num1, unsigned int num2) {/* returns 1 if num1 and num2 have a Hamming distanceExplanation / Answer
please refer below code
#include<stdlib.h>
#include<stdio.h>
int hamming_distance(unsigned int num1, unsigned int num2)
{
unsigned int result,count;
//bitwise XOR the numbers
result = num1 ^ num2;
//shift and LSB ANDing with 1
count = ((result>>31)&1)+((result>>30)&1)+((result>>29)&1)+((result>>28)&1)+((result>>27)&1)+((result>>26)&1)+((result>>25)&1)+((result>>24)&1) +
((result>>23)&1)+((result>>22)&1)+((result>>21)&1)+((result>>20)&1)+((result>>19)&1)+((result>>18)&1)+((result>>17)&1)+((result>>16)&1) +
((result>>15)&1)+((result>>14)&1)+((result>>13)&1)+((result>>12)&1)+((result>>11)&1)+((result>>10)&1)+((result>>9)&1)+((result>>8)&1) +
((result>>7)&1)+((result>>6)&1)+((result>>5)&1)+((result>>4)&1)+((result>>3)&1)+((result>>2)&1)+((result>>1)&1)+(result&1) ;
if(count <= 1)
return 1;
else
return 0;
}
int main()
{
unsigned int num1,num2;
int result;
printf("Enter Number 1 : ");
scanf("%u", &num1);
printf(" Enter Number 2: ");
scanf("%u", &num2);
result = hamming_distance(num1,num2);
if(result == 1)
{
printf(" Hamming distance is less than or equal to 1 ");
}
else
printf(" Hamming distance is greater than 1 ");
return 0;
}
please refer below output
Enter Number 1 : 5
Enter Number 2: 12
Hamming distance is greater than 1
Process returned 0 (0x0) execution time : 17.328 s
Press any key to continue.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.