I'm trying to write a program which will turn a input into binary, and the one's and two's complement of such input. I believe ~ should flip the bits and - should do the same plus adding a 1 in 1's value, yet the results are not as expected.
<!DOCTYPE html>
<html>
<head>
<script>
function doStuff(){
var numConv = document.getElementById("origNumber").value;
var aNumber = Number(numConv);
if (aNumber < 0 || aNumber > 255)
alert("Please enter a number between 0 and 255.");
else
document.getElementById("binary").innerHTML = aNumber.toString(2);
document.getElementById("ones").innerHTML = (~aNumber).toString(2);
document.getElementById("twos").innerHTML = (-aNumber).toString(2);
}
</script>
</head>
<body>
<input type="text" id="origNumber" />
<button onclick = "doStuff()">Click Me</button>
<p>Unsigned Binary:</p>
<p id="binary">The binary translation will appear here.</p> <!-- Where the binary appears -->
<p> One's Complement:</p>
<p id="ones">The one's complement will appear here.</p> <!-- Where one's complement appears -->
<p> Two's Complement:</p>
<p id="twos">The two's complement will appear here.</p> <!-- Where two's complement appears -->
</body>
</html>
In the "else" section in the script, I have lines which should convert the variable aNumber into the desired one's and two's complement, yet it doesn't.
For example, if you enter 50, the binary will be correct, but the one's turns into -51 and the two's into -50. I realize multiplying the (~aNumber) and (-aNumber) by -1 would get rid of the negative values, but it won't fix the incorrect values.
What would be a way to either fix the - and ~ operators or to circumvent them?
Note - I don't think this is the problem, but it's a problem.
You've left off a set of { }
else {
document.getElementById("binary").innerHTML = aNumber.toString(2);
document.getElementById("ones").innerHTML = (~aNumber).toString(2);
document.getElementById("twos").innerHTML = (-aNumber).toString(2);
}
Without those, the second two lines were outside the scope of influence of the if else
statement, and would run regardless of the if
test.
edit again — and the problem you're actually asking about can be solved by masking the low 8 bits of your values:
document.getElementById("ones").innerHTML = (~aNumber & 255).toString(2);
document.getElementById("twos").innerHTML = (-aNumber & 255).toString(2);
Both those operations affect the sign of the value, so if you don't mask the runtime will consider them to be negative and .toString()
will respond accordingly.