So in the python scriptA below according to geeksforgeeks.org this script is to tell me the amount of bits to be flipped to convert a to b so after i copied the count result i tried to create my own python script to test this. so the summary about my own python script was given a count and an integer variable A, flip the bits in accordance with the count to get the same bits as b without using b in equation just the count number and a ,so when i got the result integer it was not the same as integer b so i modified the script and tried again and it still didn't work any help The scriptA
if __name__ == '__main__':
a = 10
b = 20
# Function call
# Converting int to binary and counting number of bits
result = bin(a ^ b).count("1")
print(result)
And the result count is 4
So i made my script and it didn't work so can anyone create a python script that could help me thanks alot So this is my script
def flip_bits_to_match_count(a, count, b):
flipped_a = a
flips = 0
while bin(flipped_a).count("1") != count:
flipped_a ^= 1 << flips
flips += 1
return flipped_a == b
a = 10
count = 4
b = 20
matched = flip_bits_to_match_count(a, count, b)
print("Does the flipped 'a' match 'b'?", matched)
The result A is 53 not 20 that's my problem sorry i didn't post it earlier
The problem you have is that the result tells you how many bits need to be flipped, but not which ones. There is no way to use this number to unflip A to get B.
But in a way it is much simpler, because using EXOR (exclusive OR) - which is what you are doing when you do a^b, generates a number in which each binary bit tells you whether to flip a bit in a to give you the bit in b.
For example, suppose you have this
You can see that each bit in a^b tells you whether a bit in a needs flipping to generate the corresponding bit in b (and also vice versa). In fact there is symmetry here, and each can be used with either of the two remaining to generate the third. That is the beauty of exclusive or (and why it has an imortant role in encryption).