Flipping the binary bits in Python

A binary value is a combination of 0’s and 1’s. For instance, the binary value of 12(decimal) is 1100(binary). After flipping the binary bits it looks like 0011. In this tutorial, we are going to write a Python program for flipping the binary bits.

Ways for flipping binary bits

  • Using Loops: By iterating each and every bit we check if the bit is 1 if true we change the bit 1 to bit 0 and vice-versa.
    bits = '1010'
    filp_bits = '' 
    
    for i in bits:
        if i == '0':
            filp_bits += '1'
        else:
            filp_bits += '0'
    		
    print("Binary value after flipping the bits is: ", filp_bits)
    

    Output

    Binary value after flipping the bits is: 0101
  • Using replace() method: In Python, strings have an in-built function replace, which replaces the existing character with a new character.
    bits = '10100001'
    filp_bits = bits.replace('1','x') # replace 1 with x
    filp_bits = filp_bits.replace('0','1') # replace 0 with 1
    filp_bits = filp_bits.replace('x','0') # replace x with 0
        
    print("Binary value after flipping the bits is: ", filp_bits)
    

    Output

    Binary value after flipping the bits is: 01011110

Using List:

bits = '100000001'
filp_bits = ''.join(['1' if i == '0' else '0' for i in bits]) 
    
print("Binary value after flipping the bits is: ", filp_bits)

Output

Binary value after flipping the bits is: 01111111

Also, read

Leave a Reply

Your email address will not be published. Required fields are marked *