Taking a binary input from the user in python for bitwise operations

AgarwalShashank picture AgarwalShashank · Apr 10, 2015 · Viewed 7k times · Source
N,M=raw_input().split(' ')
N=int(N,2)
M=int(M,2)
print N|M

Code converts initial input to binary and then applies bitwise or. However what I require is a way to receive the initial inputs in binary itself.

If the input is

111 101

The output given is 7. The output I want is 111|101 which is 111.

Answer

Martijn Pieters picture Martijn Pieters · Apr 10, 2015

Just format the output back to binary:

print format(N|M, 'b')

This uses the format() function to produce a binary string again; the 'b' format produces a base-2 binary output:

>>> format(7, 'b')
'111'

If you needed to preserve the original inputs exactly as typed, then assign the output of the int() calls to new variables:

binary1, binary2 = raw_input().split(' ')
N = int(binary1, 2)
M = int(binary2, 2)
print '{}|{} makes {:b}'.format(binary1, binary2, N|M)

Here I used the str.format() method to produce an output string; the same formatting instructions can be used, within a simple templating framework; the output of N|M is slotted into the last {} placeholder which formats the value to a binary representation.