Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Add two binary numbers (returning binary)

I have two inputs in binary, and I'm returning the addition result in binary as well.

var addBinary = function(a, b) {
    var dec = Number(parseInt(a, 2)) + Number(parseInt(b, 2));
    return dec.toString(2);
};

For some insanely big binary like

a = 10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101

b = 110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011

I'm outputting

110111101100010011000101110110100000011101000101011000000000000000000000000000000000000000000000000

where the supposed correct output is

110111101100010011000101110110100000011101000101011001000011011000001100011110011010010011000000000

Is it because of overflow? If so, what are the restrictions in Javascript for binary addition overflow? Sorry for the bunch of 1's and 0's.

like image 372
patrickhuang94 Avatar asked Nov 01 '16 01:11

patrickhuang94


People also ask

How do you add two binary numbers?

How To Do Binary Addition? Step 1: First consider the 1's column, and add the one's column,( 1+1 ) and it gives the result 10 as per the condition of binary addition. Step 2: Now, leave the 0 in the one's column and carry the value 1 to the 10's column.

What happens when you add two binary numbers?

Binary addition is much like your normal everyday addition (decimal addition), except that it carries on a value of 2 instead of a value of 10. For example: in decimal addition, if you add 8 + 2 you get ten, which you write as 10; in the sum this gives a digit 0 and a carry of 1.

How do you sum binary numbers in Java?

For this example, you can simply do: Integer. toString(0b1010 + 0b10, 2); This will add the two in binary, and Integer.


1 Answers

instead of dealing with binary, we can convert them to decimal numbers and perform any arithmetic operation then convert back to binary again.

function calculateBinary(expr){
    let [pre,post]=expr.split(/[+|\-|\*|\/]/).map(binary=>parseInt(parseInt(binary, 2).toString(10).trim()));
    let sign=expr.match(/[+|\-|\*|\/]/)[0];
    let res=eval(pre+sign+post);
    return res.toString(2);
}
console.log(calculateBinary('11011+1000'))//=>100011
console.log(calculateBinary('1000-0100'))//=>100
console.log(calculateBinary('1000/0100'))//=>10
console.log(calculateBinary('10*10'))//=>100
like image 199
Sheikh Salman Avatar answered Oct 21 '22 13:10

Sheikh Salman