How do I add 2 (binary)? Python

Asked

Viewed 467 times

0

I want to add 2 to a binary number that the user enters and then add 2 binary values. EX: 111001 - 110001, I make the complement of 2 in the second number and then I make the sum of these values, I cannot even make the complement of 2, much less the sum. my code:

c1=""
c2=""
print("O programa fará o complemento de 2 no valor inserido")
b =  input("Digite um número binário: ")
for i in range(len(b)):
    if(b[i] == "0"):
        c1 = c1 + "1"
    elif(b[i] == "1"):
        c1 = c1 + "0"
if(c1[-1] == "0"):
   c1[-1] = str(1)
   
tamanho = len(c1)-1
for i in range(tamanho+1):
  print(i)
  print(tamanho)
  c2 = c2 + c1[i]
print("inicio:",b)
print("c1:",c1)
print("c2:",c2)
  • To do the operation of a binary number with a decimal or other binary you can do respectively n = bin(int('0101', 2) + 2) and n = bin(int('111001', 2) + int('10', 2)).

  • but how do I add 2? without using a function?

  • 1

    @Marcusloureiro, I believe it is that you seek

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.