javascript convert number to binary
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
dec2bin(1); // 1
dec2bin(-1); // 11111111111111111111111111111111
dec2bin(256); // 100000000
dec2bin(-256); // 11111111111111111111111100000000
javascript convert number to binary
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
dec2bin(1); // 1
dec2bin(-1); // 11111111111111111111111111111111
dec2bin(256); // 100000000
dec2bin(-256); // 11111111111111111111111100000000
binary addition javascript
function binaryAddition(a,b){
var result = "",
carry = 0;
while(a || b || carry){
let sum = +a.slice(-1) + +b.slice(-1) + carry; // get last digit from each number and sum
if( sum > 1 ){
result = sum%2 + result;
carry = 1;
}
else{
result = sum + result;
carry = 0;
}
// trim last digit (110 -> 11)
a = a.slice(0, -1)
b = b.slice(0, -1)
}
return result;
}
// Tests
[
["0","0"],
["1","1"],
["1","0"],
["0","1"],
["10","1"],
["11","1"],
["10","10"],
["111","111"],
["1010","11"]
].forEach(numbers =>
document.write(
numbers[0] + " + " +
numbers[1] + " = " +
binaryAddition(numbers[0], numbers[1]) +
" <mark> (" +
parseInt(numbers[0], 2) + " + " +
parseInt(numbers[1], 2) + " = " +
parseInt(binaryAddition(numbers[0], numbers[1]),2) +
")</mark><br>"
)
)
document.body.style="font:16px monospace";
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us