Write a Python program to calculate the Hamming distance between two given values


  1. Use the XOR operator (^) to find the bit difference between the two numbers
  2. Use bin() to convert the result to a binary string
  3. Convert the string to a list and use count() of str class to count and return the number of 1s in it

This is a Python program that calculates the Hamming distance between two integers entered by the user.The program first prompts the user to enter two integers a and b using the input() function and converts them to integers using the int() function.

The bitwise XOR operator ^ is used to get the bitwise difference between a and b. Then the bin() function converts the resulting integer into a binary string. The count() method of the string is then used to count the number of 1's in the binary string, which gives us the Hamming distance between a and b. The result is then printed to the console using the print() function.

Source Code

a = int(input("Enter the A Number :"))
b = int(input("Enter the B Number :"))
res = bin(a ^ b).count('1')
print("Hamming distance between",a,"and",b,"is",res)

Output

Enter the A Number :23
Enter the B Number :45
Hamming distance between 23 and 45 is 4

Example Programs