...

View Full Version : binary addition problem



Artline N
01-22-2006, 03:18 PM
Hello,

I must make a webpage that can add binary numbers. first I ask 2 decimal numbers, than the javascript convert them to binary numbers, and then they must be added by clicking the "+" button. I've allready done the 2 first steps, but I'm struggeling with the adding itself.
Can somebody help me with this?
Here is the code:


<html>
<HEAD>
<meta name=vs_defaultClientScript content="JavaScript">
<SCRIPT LANGUAGE="JavaScript">

function toBin(form) {
num = parseInt(form.num.value);
form.amount.value = num.toString(2);
}

function plus_onclick() {
Uitkomst.value = Form1.bin1.value + Form2.bin2.value
}
</SCRIPT>
</HEAD>
<BODY>
<form name=numform ID=Form1>
<p>
<input ID=Getal1 type=text name=num size=8 >&nbsp;&nbsp;
<input ID=omzet1 type=button value=" = " onclick="toBin(this.form)" >&nbsp; &nbsp;
<input ID=bin1 type=text name=amount size=15 > </p>
<p>
</form>
<form name=numform ID=Form2>
<input id=Getal2 type=text size=8 name=num>&nbsp;&nbsp;
<input id=omzet2 type=button value=" = " onclick="toBin(this.form)">&nbsp; &nbsp;
<input id=bin2 type=text size=15 name=amount>
</P>
</form>
<hr width="100%" size=1>
<input id=plus type=button value=" + " onclick="return plus_onclick()">&nbsp;
<input id=min type=button value=" - ">&nbsp;
<input id=Uitkomst
type=text>

</BODY>
</html>

:thumbsup: Tnx
Artline N

vwphillips
01-22-2006, 04:17 PM
<html>
<HEAD>
<meta name=vs_defaultClientScript content="JavaScript">
<SCRIPT LANGUAGE="JavaScript">

function toBin(form) {
num = parseInt(form.num.value);
form.amount.value = num.toString(2);
}

function plus_onclick() {
Uitkomst.value = (parseInt(Form1.num.value) + parseInt(Form2.num.value)).toString(2);
}
</SCRIPT>
</HEAD>
<BODY>
<form name=numform ID=Form1>
<p>
<input ID=Getal1 type=text name=num size=8 >&nbsp;&nbsp;
<input ID=omzet1 type=button value=" = " onclick="toBin(this.form)" >&nbsp; &nbsp;
<input ID=bin1 type=text name=amount size=15 > </p>
<p>
</form>
<form name=numform ID=Form2>
<input id=Getal2 type=text size=8 name=num>&nbsp;&nbsp;
<input id=omzet2 type=button value=" = " onclick="toBin(this.form)">&nbsp; &nbsp;
<input id=bin2 type=text size=15 name=amount>
</P>
</form>
<hr width="100%" size=1>
<input id=plus type=button value=" + " onclick="return plus_onclick()">&nbsp;
<input id=min type=button value=" - ">&nbsp;
<input id=Uitkomst
type=text>

</BODY>
</html>

Kor
01-22-2006, 04:39 PM
Here's a clue

parseInt() is not only a method to transform a string into an integer, but to transform it using any base

parseInt(string,base)

for instance
var n = 12;
var nbin = n.toString(2);//changes decimal to binary = '1100'
var ndec=parseInt(nbin,2);//changes back from binary to decimal =12

Lerura
01-22-2006, 05:02 PM
1.

You can't add binary numbers straight.
javascript understands 3 numberformats:

octal(8):
numbers with an initial 0
e.g 015 (equal to 13 in decimal)

hexadecimal(16)
numbers with an initial 0x
e.g 0x1A (equal to 26 in decimal)

and decimal(10)
numbers with an initial 1 - 9
e.g 97

in you case you must first add the numbers, and then convert them.
2.

when refering to a object in a form you must use:
document.formNAME.objectNAME.property
where formname is the Name of the form (not the ID) and the same with the object

if you want to refer to the ID you must use document.getElementById('objectID')

3.

toString will create a string that contains the number.
and adding strings will place them one after the other.

e.g. "11" + "22" = "1122"
while 11 + 22 = 33

you can use
Num=Num*1; to convert a string that contains only a number in one of the above formats (8,10,16), to a real decimal number.

Kor
01-22-2006, 05:13 PM
my clue was clear. The esiest way (even it has no meaning - this is a homework for sure) is to

decimal > to binary> show the binary > to decimal again > add > show the result (decimal or binary)

Maybe the teacher whants to know if it's student knows how to transform numbers from a base to another using javascript methods.

Or maybe the teacher whants to know if it's student knows the binary add algorithm... In this case, things goes a little bit more intricate in javascript (as it was not designed for this kinda operations)

Artline N
01-23-2006, 10:58 AM
Or maybe the teacher whants to know if it's student knows the binary add algorithm... In this case, things goes a little bit more intricate in javascript (as it was not designed for this kinda operations)

Indeed, I'm trying to create a program that does the "binary add algorithm"... But I think that I just will tell my teacher that it is not easy to do this in javascript and that he must give me another assignment. (But I can do the binary adding in Turbo Pascal) Is there an easy way to translate it?


PROGRAM records_optellen_van_2_arrays_in_een_3e_array;

USES CRT;

TYPE getal1 = ARRAY[1..50] of INTEGER;
TYPE getal2 = ARRAY[1..50] of INTEGER;
TYPE getal3 = ARRAY[1..51] of INTEGER;
VAR loop, number, number2, temp : INTEGER;
get1 : getal1;
get2 : getal2;
get3 : getal3;

BEGIN
temp := 0;
WRITE('Hoe lang zijn je 2 getallen? (max. 50): ');
READLN(number);
WRITELN('Geef de cijfers van het eerste binaire getal. (Enkel 1 en 0 ingeven!)');
FOR loop := 1 TO number DO
BEGIN
WRITE(loop,'e cijfer: ');
READLN(get1[loop]);
WRITELN('');
END;
WRITELN('Alle cijfers van het eerste getal zijn ingevoerd.');
WRITELN('Het eerste getal is:');
FOR loop := 1 TO number DO
BEGIN
WRITE(get1[loop]);
END;
WRITELN('');
WRITELN('Geef de cijfers van het tweede binaire getal. (Enkel 1 en 0 ingeven!)');
FOR loop := 1 TO number DO
BEGIN
WRITE(loop,'e cijfer: ');
READLN(get2[loop]);
WRITELN('');
END;
WRITELN('Alle cijfers van het tweede getal zijn ingevoerd.');
WRITE('Het eerste getal is: ');
FOR loop := 1 TO number DO
BEGIN
WRITE(get1[loop]);
END;
WRITELN('');
WRITE('Het tweede getal is: ');
FOR loop := 1 TO number DO
BEGIN
WRITE(get2[loop]);
END;
WRITELN('');
number2 := number + 1;
FOR loop := number2 DOWNTO 1 DO
BEGIN
IF number = 0 THEN
get3[loop] := temp
ELSE
BEGIN
get3[loop] := get1[number] + get2[number] + temp;
temp := 0;
IF get3[loop] = 2 THEN
BEGIN
temp := 1;
get3[loop] := 0;
END;
IF get3[loop] >= 3 THEN
BEGIN
temp := 1;
get3[loop] := 1;
END;
number := number - 1;
END;
END;
WRITE('Het derde getal is : ');
FOR loop := 1 TO number2 DO
BEGIN
WRITE(get3[loop]);
END;
WRITE(readkey);
END.

thanks for all the help!

Kor
01-23-2006, 11:48 AM
Intricate job. Well I know that adding two binary algorithm looks like:

1. adding vertically on columns, from right to left, keeping in mind that

0+0 =0
1+0 = 0+1 =1
1+1 = 10 (that means, more precisely, 0 and carrying 1 to the next left column)

1010
+1111
______
11001

That means if you have two "binary numbered" strings you should:

- split the strings to 2 arrays using split('');
- circle through the arrays from bottom to top
- transform each element in decimal number ("0" to 0 and "1" to 1);
- set the new operation rules ( 0+0 =0, 1+0 = 0+1 =1, 1+1 = 0 carry1)
- "add" the correspondent arrays' elements, from bottom to top, one by one following the new rules
- transform each result element in a string (as element belonging to the result new array).
- join() the elements of the result array.

Does anyone knows other method?

As you see it looks like an intricate job... javascript is a bad math operator, It was not designed for that.

liorean
01-23-2006, 03:12 PM
Let me tell you a little secret:

To the JavaScript engine, there is no such thing as a decimal number. There is just an input and output format that is decimal. The actual number is always in binary.

With this in mind, it should be easy to do things:
- Input a decimal number into a variable, let's call it number1
- Input a decimal number into a variable, let's call it number2
- Output a string representing number1 in binary.
(Note: number1 is not changed, just output at radix 2 instead of 10)
- Output a string representing number2 in binary.
- Add number1 and number2 together and store the result in a variable, let's call it number3
- Output number3 in decimal or binary as requested.

However, if that's the wanted solution or not depends on what the teacher want. If he wants you to show you understand binary numbers, how adding them works, then it's probably not the solution he wants. If he wants to know that you know the constructs needed to perform this action in actual binary (well, as I pointed out earlier the numbers are always binary...) then no, it circumvents them by using built ins. If he wants to know that you know how to handle forms values and converting to numbers, then yes. Or one of the other possible reasons he could have for asking this question in particular...

Kor
01-23-2006, 04:28 PM
If he wants you to show you understand binary numbers, how adding them works, then it's probably not the solution he wants.

:D Correct. liorean is absolutelly right. Javascript is not exactly the proper medium to show your teacher that you have understood the binary math operations....

Or maybe he wants to see how you can avoid all these, on using the methods I have already shown you...

Anyway... Keep in mind that javascript is not exactly the best medium for a complex and fast math calculation. Whenever is possible, use a server side application to do that (speed and accuracy are higher) and let javascript do only the "small local adjustments"

BaldEagle
01-23-2006, 05:30 PM
You have received some good advice here, but I will through one more thought into the mix. If the idea is to recreate the workings of a binary adder then you need to take a look at bitwise shifting. Bitwise shifting implies mulipication and division however when it comes to keeping track of the carry bits it will serve the purpose.

if adding only two numbers together this approach would have little meaning but if you want to create a binary adder that can add four or more numbers together then this would be the way to go.

00001
00001
this addition would genrate a carry bit which would then be added to the next stage thus making the output be 00010. Easy enough.

00001
00001
00001
00001
This situation is a bit different though because you will actually generate 2 carries. When you hit the second carry you would do this
carrybit << 1 which would now give you 10 as your carry and addding the columns would produce 00100.

It would be a little work but would be the closest to emulating a binary adder.

BaldEagle

[edit] I'll add one thing to this, the var holding your carries would actually become a binary counter and you would have to account for this. As I said and many before said this is not what javascript is best at and would be a monumental task. How yo do this is really dependent on what your teacher/instructor wants from you.

liorean
01-23-2006, 09:34 PM
Well, if you have to use binary number representation (a string in other words) I can see a way that should work:

- Pad the binary number strings to same size by adding zeroes in front of the smaller one.
- Split the binary number strings into single character arrays num1 and num2.
- Have a separate memory variable, starting off as 0.
- Have a results variable starting off as the empty array.
- For each character in both strings, from the end (you can pop them from the array if you wish) do the following:

Concatenate last element of num1 (pop it), last element of num2 (pop it) and memory into a three character string.

'000': Add '0' to the end of the results array (you can push it onto it if you wish), set memory to 0.

'111': Push '1' onto the results array, set memory to 1.

'100','010','001': Push '1' onto the results array, set memory to 0.

'110','101','011': Push '0' onto results, set memory to 1.


- Reverse the results array and join it by the empty string.

BaldEagle
01-23-2006, 10:59 PM
I am sure some or most of you have figured this out by now, but I will say it anyway. MY IDEA SUCKED. It gets out of control in a hurry.

BaldEagle



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum