Reputation: 33
function addBinary(a,b) {
let sum= a+b
if (sum<0){
sum=0xffffffff+sum+1
}
return parseInt(sum).toString(2)
}
and especially the logic of how 0xffffffff has been used to achieve same result
function decimalToBinary(decimal){
return (decimal >>> 0).toString(2);
}
function addBinary(a,b) {
return decimalToBinary(a+b);
}
Upvotes: -1
Views: 65
Reputation: 349956
The >>> operator always interprets the given number as an unsigned 32 bit number. When the second operand is 0, nothing changes to that and the result is unsigned.
So for instance, -1 in binary is 0xffffffff in signed 32-bit, where the most significant bit (at the left) is the sign bit. But because exceptionally the >>>
does not interpret that as a sign bit, it actually is seen as a positive number, i.e. 0xffffffff. Compared to the original -1 that is 0x100000000 more! This is always the difference for negative inputs. For -2 you'll get 0xfffffffe, for -3 you'll get 0xfffffffd, ...etc.
The first function emulates this. If sum
is negative, we must do something, as the other function (using >>>
) will never return a negative number.
The idea is to add that 0x100000000 difference. In fact, the author of this function was prudent, and evidently didn't want to work with numbers that exceed the 32 bit range, so 0x100000000 was off the board (it uses 33 bits). But one can split the job into parts. We can add one less (0xffffffff) to the sum, and then add the remaining 1. This is just a theoretical game though. In JavaScript there is no problem in adding 0x100000000, so they could just as well have done that. In other languages however, those that use 32 bit numbers, it would be necessary to first add 0xffffffff and only then 1.
Upvotes: 1