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

Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63
  • 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. – Daniel Porteous Jun 17 '16 at 06: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. – Arindam Roychowdhury Jun 20 '16 at 08:19

2 Answers2

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

Daniel Porteous
  • 5,536
  • 3
  • 25
  • 44
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'
Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63