I am writing a basic calculator for my computer science class which takes in a number between 0-255 and converts it to binary, one's complement, and two's complement. Me and one other student have been working on this together and we are both stuck at the two's complement, it is producing the wrong value. For example if we type in 11 the two's complement should be "1111 1011" but i am getting "1111 0101" and I am not sure what is wrong?
I have started a demo at jsbin.com and I am hoping that someone here can really save my life (and my grade) and tell me what me and my coding partner are doing wrong.
jsbin -> http://jsbin.com/juqevomiliwo/1/edit
Also, I would really like to add in some error checking such as if a user inputs a negative number or if a user inputs a value that is not within the value range of 0-255 could someone assists me with that as well? I would really like to have a pop up say, "i am sorry you need to input a value between 0-255"
I apologize for asking so much but i don't know where else to turn! I have gone to stackoverflow so many times to help assist me with issues and this is my first time posting a problem that I don't know how to solve!
Thank you all so much for your time and your assistance!
-Martin
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Group Project</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Group Project 1</h1>
<p>Enter a number between 0 and 255 <input id="theInput" type="text" /> <button onclick="doSomething()">Show Binary</button> </p>
<p>Unsigned Binary: <span id="binaryOutput"></span></p>
<p>One's Complement: <span id="onesOutput"></span></p>
<p>Two's Complement: <span id="twosOutput"></span></p>
<script>
function doSomething(){
var i = document.getElementById('theInput').value; //gets number from input box and sets it to i
var binary = pad(Number(i).toString(2), 8); //converts i to binary and pads with leading zeros until 8 digits long
var ones = binary.toString(2).replace(/1/g, 'a').replace(/0/g, '1').replace(/a/g, '0');
var twos = pad((Number(ones) + 1), 8);
document.getElementById('binaryOutput').innerHTML = fancy(binary); //puts the binary in the Unsigned Binary field
document.getElementById('onesOutput').innerHTML = fancy(ones); //puts the ones compliment in the One's Complement field
document.getElementById('twosOutput').innerHTML = fancy(twos); //puts the twos compliment in the Two's Complement field
}
//adds leading zeros to achieve width
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
//adds space every four digits
function fancy(b) {
return b.replace( /\d{4}/g, '$& ' ).replace( /\s$/,'');
}
</script>
</body>