0

I am trying to remake the sum operator of python, I already have a working version that uses strings:

def sum(a, b):
    a, b = conversionBin(a), conversionBin(b)
    if len(a) > len(b):
        c = len(a)
        while len(b) != len(a):
            b = "0" + b
    else:
        c = len(b)
        while len(b) != len(a):
            a = "0" + a
    L = ""
    r = False
    i = c-1
    for _ in range(c):
        if int(a[i]) and int(b[i]):
            if r:
                L = "1" + L
            else:
                L = "0" + L
                r = True
        elif int(a[i]) != int(b[i]):
            if r:
                L = "0" + L
            else:
                L = "1" + L
        else:
            if r:
                L = "1" + L
                r = False
            else:
                L = "0" + L
        i -= 1
    if r:
        L = "1" + L
    return conversionInt(L)

and for complexity reasons, I'd like to do it bitwise, but I don't know how to write bits directly to an integer, here's what I'm working with:

def sumBin(a, b):
    c = 32 #number of bits, I need to find a way to set this automatically later on
    r = False
    i = c - 1
    d = 0 #variable in which I want to write the bits
    for _ in range(c):
        if ((a >> i) & 1) & ((b >> i) & 1):
            if r:
                #sets n-th bit of d to 1
                pass
            else:
                r = True
        elif (((a >> i) & 1) ^ ((b >> i) & 1)) and not r:
            #sets n-th bit of d to 1
            pass
        elif r:
            #sets n-th bit of d to 1
            r = False
        i -= 1
    if r:
        #sets n-th bit of d to 1
        pass
    return d

so how can I directly write bits to an integer in python? Thank you in advance if you can answer my question

1ups_
  • 1

0 Answers0