Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How to flip the bits of a number according to the count

$
0
0

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 helpThe 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 alotSo 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 == ba = 10count = 4b = 20matched = 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


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>