Search code examples
pythonmathbinarybit

How to make all the bits inverted in python?


I want to convert these binary representation as follows.

"1111" -> "0000"
"1010" -> "0101"

Solution

  • To convert

     "0100" to "1011",         simply 0100(your input string) ^ 1111(maskbit)         = "1011"
    
     "11110000" to "00001111", simply 11110000(your input string) ^ 11111111(maskbit) = "00001111" 
    

    We can see a pattern here,

    len(mask bit) = len(binary input string)

    Based on the above observations,

    def invertBits(num): 
    
         mask='1'*len(num)                       #This produces bit mask needed for the conversion
         answer=int(num,2)^int(mask,2)           #Inversion process happens here (XOR)
    
         print(answer,bin(answer).lstrip("0b")); #This would give both the integer equivalent and the pattern of the inverted bits as a string
    
    invertBits("0100")                           #The output will be "11 1011"
    

    The method int(num,2) takes "num" argument as a string and base="2" here(binary format)