9/14 bug? symantics XOR syntax


When solving the problem on paper, I came up with 0b011, which, I suppose is the same as 0b11? The picture of my result shows it isn't. Please advise?


For practice, print the result of using ^ on 0b1110 and 0b101 as a binary string. Try to do it on your own without using the ^ operator.

print bin(0b1110 ^ 0b101)



Try to do it on your own without using the ^ operator.

This is a bit convoluted, but the algorithm returns a correct result for a maximum 8 bits.

def a_xor_b(ab):
    # fill a list with 8 '0's
    bp = list('0'*8)
    # convert inputs to 8 bits with possible leading zeros
    bits = [(bp + list(ab[i][2:]))[-8:] for i in range(2)]
    # preload the results list with '0's (clone of bp)
    xor = bp[:]
    # compare bits at corresponding index
    for i in range(8):
        # both bits cannot be zero
        if bits[0][i] != 0 and bits[1][i] != 0:
            # difference may be 1 or -1 which is set to 1 (0 ignored)
            xor[i] = str(abs(int(bits[0][i]) - int(bits[1][i])))
    # remove leading zeros
    for i in range(len(xor)):
        if xor[i] == '1':
            xor = xor[i:]
    # return result as a string representation of a binary
    return '0b'+''.join(xor)

# pass a list of 2 binary numbers in string form
print(a_xor_b([ '0b1110', '0b101' ]))     # 0b1011

The methodology is more brute force than elegant. Hopefully a Python guru will pipe in and show us how to improve upon and simplify this program.


share mine it looks complicated but might no limited, hope someone make it concisely. :yum:

def a_xor_b(a,b):
    str_a = str(bin(a))
    str_b = str(bin(b))
    str_len = len(str_a) if len(str_a)>=len(str_b) else len(str_b)
    str_a_gap = len(str_a)-len(str_b) if len(str_a)<=len(str_b) else 0
    str_b_gap = len(str_a)-len(str_b) if len(str_a)>=len(str_b) else 0
    str_a = ['0' for i in range(0,abs(str_a_gap))] + [str_a[i] for i in range(2,str_len-abs(str_a_gap))]
    str_b = ['0' for i in range(0,abs(str_b_gap))] + [str_b[i] for i in range(2,str_len-abs(str_b_gap))]
    str_final = '0b'+''.join(['0' if str_a[i] == str_b[i] else '1' for i in range(str_len-2)])
    return str_final


given that we're allowed to assume that & and ~ are defined

def or_(a,b):
    return bin(~(~a & ~b))    

def xor_(a,b):
  return bin((a|b)&~(a&b))