Daerik Fisher
Daerik Fisher

Reputation: 293

Binary subtraction in Java

I'm trying to make a binary calculator that subtracts two binary numbers (only with base 2) without parsing it.

Can anyone help me with the situation that I have zero in the upper number and one in the lower number, I can't seem to write the code for it.

for (int i = ss.length()-1; i > -1; i--)
        {
            if(s.charAt(i)=='0' && ss.charAt(i)=='0') sb.append("0");
            else if (s.charAt(i)=='1' && ss.charAt(i)=='0') sb.append("1");
            else if (s.charAt(i)=='1' && ss.charAt(i)=='1') sb.append("0");
            else
            {
                sb.append("1");
                doit(s,i+1,sb);
            }
        }

        for (int i = s.length() - ss.length(); i >-1; i--) 
        {
            sb.append(s.charAt(i));
        }

        ArrayList<Character> res = new ArrayList<>();
        for (int i =  sb.length()-1; i > -1; i--)
        {
            res.add(sb.charAt(i));
        }
        System.out.println(res);
    }
    public static void doit(StringBuilder s, int i, StringBuilder sb)
    {
        for (int j = i; j > -1; j--)
        {
            if(s.charAt(j)=='0')
            {
                s.setCharAt(j, '1');
            }
            else
            {
                s.setCharAt(j, '0');
                break;
            }
        }
    }

Upvotes: 1

Views: 8730

Answers (3)

saswatmantri
saswatmantri

Reputation: 1

import java.util.Scanner;
class binary_diff
{
    public String diff(String st1,String st2)
    {
        String nst="",max="";char b='0';boolean tf=(st1.length()>=st2.length());
        int l1=st1.length(),l2=st2.length();
        if(l1<l2)
        for(int a=1;a<=l2-l1;a++)
        st1='0'+st1;

        else if(l2<l1)
        for(int a=1;a<=l1-l2;a++)
        st2="0"+st2;
        if(!tf)for(int a=l1-1;a>=0;a--)
        if(st1.charAt(a)!=st2.charAt(a))
        if(st2.charAt(a)=='1'){max=st2;st2=st1;st1=max;break;}

        for(int a=st1.length()-1;a>=0;a--)
        {
            if(st1.charAt(a)=='1' && st2.charAt(a)=='0')
            {
                if(b=='1')
                {nst='0'+nst;b='0';}
                else
                nst='1'+nst;
            }

            else if(st1.charAt(a)==st2.charAt(a) && st2.charAt(a)=='1')
            {
                if(b=='1')
               {nst='1'+nst;b='1';}
                else
                nst='0'+nst;
            }

            else if(st1.charAt(a)=='0' && st2.charAt(a)=='1')
            {
                if(b=='1')
                nst='0'+nst;
                else
                {nst='1'+nst;b='1';}
            }

            else
            {
                if(b=='1')
                nst='1'+nst;
                else
                nst='0'+nst;
            }
        }
        return nst;
    }

    public static void main()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the two numbers");
        String s1=sc.next();
        String s2=sc.next();
        binary_diff bd=new binary_diff();
    System.out.println(bd.diff(s1,s2));
    }
}

Upvotes: -1

full.stack.ex
full.stack.ex

Reputation: 1747

You can do it strictly bitwise, right to left, like at least some chips do. The tricky knowledge is a five-column table: (a,b, carry bit from prior position) -> (result, new carry bit). You don't actually borrow from the higher-level positions; you carry the underverflow into those instead. See table 2.4 here:

http://books.google.com.ua/books?id=vpWS-s4d5vMC&pg=PA25&lpg=PA25&dq=binary+subtraction+table+carry&source=bl&ots=458JWgZl8v&sig=sjuXedv96KCbNWmxQAPNQo7iuRw&hl=en&sa=X&ei=i-6jUI7IB8jusgay8IDQDQ&ved=0CBwQ6AEwAA#v=onepage&q=binary%20subtraction%20table%20carrysubtract&f=false

Define two methods: (a,b, carry bit from prior position) -> result and (a,b, carry bit from prior position) -> new carry bit, and apply them right to left.


Alternative: invert your second argument according to the rules here: http://simple.wikipedia.org/wiki/Negative_binary_numbers .

Then add #1 to the inverted #2 :).

PS. Who said it's a bad assignment :)?

Upvotes: 0

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51551

Binary rules of subtraction.

1 - 1 = 0
0 - 0 = 0
1 - 0 = 1
0 - 1 = 1 (needs a carry bit from a higher bit position.  
    You might have to check several higher bits before you 
    find the carry bit.  -1 otherwise.)

Upvotes: 2

Related Questions