Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for binary arithmetic in Java

On paper, binary arithmetic is simple, but as a beginning programmer, I'm finding it a little difficult to come up with algorithms for the addition, subtraction, multiplication and division of binary numbers.

I have two binary numbers stored as strings, assume that any leading zeroes have been dropped. How would I go about performing these operations on the two numbers?

Edit: I need to avoid converting them to an int or long.

like image 355
Tyler Treat Avatar asked Mar 09 '10 21:03

Tyler Treat


2 Answers

Binary string to int:

int i = Integer.parseInt("10101011", 2);
int j = Integer.parseInt("00010", 2);

Then you can do anything you please with the two ints, eg:

i = i + j;
i = i - j;

And to get them back to a binary string:

String s = Integer.toBinaryString(i);
like image 85
Paul Avatar answered Oct 14 '22 11:10

Paul


The algorithms, from wikipedia:

Addition:

The simplest arithmetic operation in binary is addition. Adding two single-digit binary numbers is relatively simple, using a form of carrying:

0 + 0 → 0
0 + 1 → 1
1 + 0 → 1
1 + 1 → 0, carry 1 (since 1 + 1 = 0 + 1 × 10 in binary)

Adding two "1" digits produces a digit "0", while 1 will have to be added to the next column.

Subtraction:

Subtraction works in much the same way:

0 − 0 → 0
0 − 1 → 1, borrow 1
1 − 0 → 1
1 − 1 → 0

Subtracting a "1" digit from a "0" digit produces the digit "1", while 1 will have to be subtracted from the next column. This is known as borrowing. The principle is the same as for carrying. When the result of a subtraction is less than 0, the least possible value of a digit, the procedure is to "borrow" the deficit divided by the radix (that is, 10/10) from the left, subtracting it from the next positional value.

Multiplication:

Multiplication in binary is similar to its decimal counterpart. Two numbers A and B can be multiplied by partial products: for each digit in B, the product of that digit in A is calculated and written on a new line, shifted leftward so that its rightmost digit lines up with the digit in B that was used. The sum of all these partial products gives the final result.

Since there are only two digits in binary, there are only two possible outcomes of each partial multiplication:

* If the digit in B is 0, the partial product is also 0
* If the digit in B is 1, the partial product is equal to A

For example, the binary numbers 1011 and 1010 are multiplied as follows:


            1 0 1 1   (A)
          × 1 0 1 0   (B)
          ---------
            0 0 0 0   ← Corresponds to a zero in B
    +     1 0 1 1     ← Corresponds to a one in B
    +   0 0 0 0
    + 1 0 1 1      
    --------------- 
    = 1 1 0 1 1 1 0
like image 42
iTayb Avatar answered Oct 14 '22 11:10

iTayb