Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Subtraction - Python

Tags:

python

binary

I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I've found on this website).

    maxlen = max(len(s1), len(s2))

    s1 = s1.zfill(maxlen)
    s2 = s2.zfill(maxlen)

    result  = ''
    carry   = 0

    i = maxlen - 1
    while(i >= 0):
        s = int(s1[i]) - int(s2[i])
        if s <= 0:
            if carry == 0 and s != 0:
                carry = 1
                result = result + "1"
            else:
                result = result + "0"
        else:
            if carry == 1:
                result = result + "0"
                carry = 0   
            else:
                result = result + "1" 
        i = i - 1


    if carry>0:
        result = result + "1"

    return result[::-1]

The program works fine with some binaries subtraction but it fails with others. Can someone please help me because I can't find the mistake? Thanks a lot.

like image 555
user2328079 Avatar asked Dec 29 '14 21:12

user2328079


People also ask

How do you subtract two binary?

Binary subtraction of numbers can be done by adding the 2's complement of the second number to the first number. Binary subtraction is just the binary addition of a negative number.

How do you substract in binary?

To subtract a larger number from a smaller one, switch the order of the numbers, do the subtraction, then add a negative sign to the answer. For example, to solve the binary problem 11 - 100, solve for 100 - 11 instead, then add a negative sign to the answer.

Is there a subtraction function in Python?

Python provides the subtraction operator - to subtract one object from another. The semantics of the subtraction depends on the operands' data types.


1 Answers

Short answer: Your code is wrong for the case when s1[i] == s2[i] and carry == 1.

Longer answer: You should restructure your code to have three separate cases for s==-1, s==0, and s==1, and then branch on the value of carry within each case:

if s == -1:  # 0-1
    if carry == 0:
        ...
    else:
        ...
elif s == 0:  # 1-1 or 0-0
    if carry == 0:
        ...
    else:
        ...
else:  # 1-0
    if carry == 0:
         ...
    else:
        ...

This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.

like image 184
augurar Avatar answered Sep 24 '22 03:09

augurar