Akash Dubey
Akash Dubey

Reputation: 53

How to make all the bits inverted in python?

I want to convert these binary representation as follows.

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

Upvotes: 0

Views: 619

Answers (4)

hari9602
hari9602

Reputation: 46

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)

Upvotes: 1

jinwon2
jinwon2

Reputation: 84

I'm not good at python but I think this is right because it worked on my computer.

num = input()
answer = ""
for i in range(0, len(num)):
    if num[i] == "0":
        answer += "1"
    elif num[i] == "1":
        answer += "0"
print(answer)

input:

0000

output:

1111

Upvotes: 0

wong.lok.yin
wong.lok.yin

Reputation: 889

I have a method to do that, but it takes several type conversion. Not sure if there is better way to do that.

def f(x:str):
    return  '%04d' % int(bin(int(x, 2) ^ 15)[2:])

print(f("0000"))
print(f("0011"))
print(f("1010"))
print(f("1111"))
output:
1111
1100
0101
0000

Upvotes: 0

Shibiraj
Shibiraj

Reputation: 769

Hope you are looking something like this,

def convert(inp):
    return ''.join(['1','0'][int(i)] for i in inp)
convert('1010')

output

0101

Upvotes: 6

Related Questions