Lesson : A BIT of This OR That


Hi, instruction mentions:
" For practice, print out the result of using | on 0b1110 and 0b101 as a binary string. Try to do it on your own without using the | operator if you can help it.

So i’ve managed to do it, but something tells me that my solution is big and ugly:

#print (bin(0b1110 | 0b101))
a = bin(0b1110)
b = bin(0b101)
temp = [] 
result = []
if "0b" in a:
  a = a.replace("0b", "")
if "0b" in b:
  b = b.replace("0b", "")
for i in a:
a = temp
temp = []
for i in b:
b = temp
temp = []
if len(a) > len(b):
  d = len(a) - len(b)
  for i in range(0, d):
    b.insert(0, "0")
if len(b) > len(a):
  d = len(b) - len(a)
  for i in range(0, d):
    a.insert(0, "0")
for i, ax in enumerate(a):
  if ax == "1" or b[i] == "1":
result.insert(0, "0b")
result = "".join(result)
print a
print b
print "result =", result

Is there any way to make it less bulky? Thanks in advance!

1 Like