0

I want to do OR operation on binaries. I have the binaries in strings. E.g

>>> 110 | 001
111

I have these binaries as strings. LIke this: '110100' and '001011'

For the above inputs, I want an output : 111111

2
  • 1
    This question isn't clear. Do you mean you have a string like this "110100" which you then split in half and do the following: 110 | 100. Or do you want to do the operation on two separate binary numbers in two different strings. Commented Jun 17, 2016 at 6:00
  • @DanielWesleyPorteous I have inputs in strings. Two different inputs. Both are binaries like "101010" . Means, in string format. So how can we do any operation like AND, OR, or XOR . The basic problem is converting them into true binary before doing anything. Commented Jun 20, 2016 at 8:19

2 Answers 2

1

If you have two strings with a binary number inside them, you can simply convert them to base 10 integers and then do your binary operations inside a bin().

num1 = int("110", 2)
num2 = int("001", 2)

print(bin(num1 | num2))
# Prints 0b111

Or for your second example:

num1 = int("110100", 2)
num2 = int("001011", 2)

print(bin(num1 | num2))
# Prints 0b111111

This gives you answers in actual binary numbers inside python. For reference, I recommend this question: Binary numbers in Python

Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer. This is exactly what I was looking for. Thanks.
0

I could do what I want like this. May be there are simpler ideas.

>>> eval('0b' + '110100') | eval('0b' + '001011')
63

>>> bin(63)
'0b111111'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.