Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Javascript High School Assignment Help Decimal to Binary

1. ## Javascript High School Assignment Help Decimal to Binary

hey everyone i am new here and i will be attending college next year to become a Systems Analyst. I realize that there are times when the logic gets difficult but after exhausting myself for 20+ hours i have achieved not much and i am turning to you for help.

//** please note that i dont want someone to write the whole code as i want to learn this. i just need help with my current code for the Decimal to Binary conversion. which begins in Function funcConvert(num){ else if (mode.selectedIndex==1){}}**//

i have been learning java script for about a month now and my assignment is to make a program that will convert:

Binary to Decimal - [DONE]
Decimal to Binary - [Started]
Binary to Hex
Hex to Binary
Binary to Octal
Octal to Binary

i created a function that allows only valid keys to be pressed for each conversion, i thought that would be the hard part and i could fly through the conversions.

i was able to get Dec2Bin to work to a certain extent last night, but there were errors. both 15 and 16 were displayed as same value. if the number was even it wouldnt show the last 0, but only sometimes.

i am completely lost in my code, i cant keep track of my own variables (im sure i have more than needed) and i made a minor change and couldnt remember what it was when i came back to the code and now Dec2Bin just displays all 0's as binary output.

Code:
```<html>
<script>

function funcConvert(num){
if(mode.selectedIndex==0){
total=0
v=num.length
exp=1
for (v=num.length;v>0;v--){
total=total+(num.charAt(v-1)*exp)
exp=exp+exp
}
}
else if (mode.selectedIndex==1){
total=""
num2=0
exp=1
i=0
ii=0
while(exp<num){
exp=exp+exp
i++
}
while(ii<i){
if(num2+exp<=num){
total=total+"1"
}
else{
total=total+"0"
}
exp=exp/2
num2=num2+exp
ii++
}
}
}

function resetInput(){
document.getElementById('UInput').value = "";
warning.innerHTML=""
result.innerHTML=""
if (mode.selectedIndex==3){
warning.innerHTML="Only UPPER CASE letters."
}
}

function checkVal() {
if((mode.selectedIndex==0)||(mode.selectedIndex==2)||(mode.selectedIndex==4)){
if(event.keyCode>31 && (event.keyCode<48 || event.keyCode>49)){
return false
}
else{
return true
}
}
else if(mode.selectedIndex==1){
if(event.keyCode>31 && (event.keyCode<48 || event.keyCode>57)){
return false
}
else{
return true
}
}
else if(mode.selectedIndex==3){
if (event.keyCode > 31 && (event.keyCode < 48 || event.keyCode > 57 && event.keyCode < 65 || event.keyCode > 70)){
return false
}
else {
return true
}
}
else if(mode.selectedIndex==5){
if(event.keyCode>31 && (event.keyCode<48 || event.keyCode>55)){
return false
}
else{
return true
}
}
}

</script>

<body>

<b>Enter Value:<b>
<input type="text" id="UInput" name="string" size="25" onkeypress="return checkVal()">
<select id="mode"onchange="resetInput()">
<option>Binary to Decimal</option>
<option>Decimal to Binary</option>
<option>Binary to Hex</option>
<option>Hex to Binary</option>
<option>Binary to Octal</option>
<option>Octal to Binary</option>
</select>
<input type="button" value="Convert" onClick="funcConvert(string.value)">
<p><span id="result" style="color:navy"></span>
<p><span id="warning" style="color:red"></span>

</body>
</html>```

• Try this which is to be found not a million miles from this forum:-

http://www.javascriptkit.com/script/...nconvert.shtml

There is little point in trying to reinvent the wheel.

Have a look at this:-

Code:
```<script type = "text/javascript">
var num = 255;
var hex = num.toString(16).toUpperCase();  // hex
var oct = num.toString(8);  // octal

var octal = 0377;
var hex = 0xFF;

</script>```
You will naturally need to validate the inputs. Examples:-

if (!/(^(0x)?[A-F0-9]+\$)/i.test(hexInput.value)) { // must be a valid hex code 0-9 and A-F, optional 0x prefix
if (!/^0[0-7]+\$/.test(octalInput.value)) { // must be 0 followed by 0-7
if (!/^[01]+\$/.test(binaryInput.value)) { // only 0 and 1 allowed

You can either do this check onblur at the end of the input, or preferably onkeyup as each character is entered.

"i made a minor change and couldnt remember what it was when i came back to the code" - well, you will have learnt to retain back-up copies and when you make a change to the coding save it as a new file, and not overwrite the old one. Bugs can sometimes appear some time afterwards.

In English the personal pronoun I is spelled with a capital letter. JavaScript is also case sensitive.

“There are two kinds of failures: those who thought and never did, and those who did and never thought.” - Dr. Laurence J. Peter quotes (American "hierarchiologist", Educator and Writer, 1919-1990)

• missing an l in .shtml, incase anyone comes across this in google.

and also i realize javascript is case sensitive. ...i had quite the time figuring that one out on my own :P

thanks a million

• As long a Philip is pointing out the nice features of toString( ), don't ignore the same capabilities with parseInt:

var fromHex = parseInt( yourForm.inputField.value, 16 );
var fromOctal = parseInt( yourForm.inputField.value, 8 );
var fromBinary = parseInt( yourForm.inputField.value, 2 );
var fromDuoDecimal = parseInt( yourForm.inputField.value, 12 );

• To expand on that:-

Code:
```<p>Convert a hex, octal, binary or duodecimal value to decimal</p><br>

<form name = "myform">
Value to Convert <input type = "text" name = "inputField" onblur = "calc()">
</form>

<script type = "text/javascript">

function calc(){
var inp = document.myform.inputField.value.toUpperCase();
var fromHex = parseInt(inp, 16);
alert ("The decimal value of " + inp + " hexadecimal is " + fromHex);
if (!isNaN(inp)) {
var fromOctal = parseInt(inp, 8);
alert ("The decimal value of " + inp + " octal is " + fromOctal);
var fromDuoDecimal = parseInt(inp, 12);
alert ("The decimal value of " + inp + " duodecimal is " + fromDuoDecimal);
}
if (!/[^01]/g.test(inp)) {
var fromBinary = parseInt(inp, 2);
alert ("The decimal value of " + inp + " binary is " + fromBinary);

}
}
</script>```

• No, that doesn't quite work, Philip.

If you enter a value of, say, AA, then you get the hex conversion but because you just used isNaN(inp) on the original input prior to both the octal and duodecimal, AA is rejected and so you don't get a valid answer for the duodecimal.

Further, if you enter 99, then it *DOES* pass the isNaN(inp) test and now you get a NaN answer for the octal. (The duodecimal works fine.)

I think you are just working too hard at it:
Code:
```<p>Convert a hex, octal, binary or duodecimal value to decimal</p><br>

<form name = "myform">
Value to Convert <input type = "text" name = "inputField" onCHANGE = "calc()">
<input name=foo>
</form>

<script type = "text/javascript">

function calc()
{
var inp = document.myform.inputField.value.toUpperCase();
var fromHex = parseInt(inp, 16);
if ( !isNaN(fromHex) ) alert ("The decimal value of " + inp + " hexadecimal is " + fromHex);
var fromOctal = parseInt(inp, 8);
if ( !isNaN(fromOctal) ) alert ("The decimal value of " + inp + " octal is " + fromOctal);
var fromDuoDecimal = parseInt(inp, 12);
if ( !isNaN(fromDuoDecimal) ) alert ("The decimal value of " + inp + " duodecimal is " + fromDuoDecimal);
var fromBinary = parseInt(inp, 2);
if ( !isNaN(fromBinary) ) alert ("The decimal value of " + inp + " binary is " + fromBinary);
}
</script>```
Or, if you wanted to have fun:
Code:
```<html><head>
<script type = "text/javascript">
function calc(inp)
{
var txt = "";
for ( var base = 16; base >= 2; --base )
{
var parsed = parseInt(inp, base);
if ( !isNaN(parsed) )
txt += "The decimal value of <b>" + inp + "</b> to the base <b>"
+ base + "</b> is <b>" + parsed + "</b><br />";
}
document.getElementById("SHOWME").innerHTML = txt;
}
</script>
<body>
<form onsubmit="calc(this.inputField.value);return false;">
Value to Convert <input name="inputField">
<p>
<input type=button value="Show me" onclick="calc(this.form.inputField.value);">
</form>
<hr>
<div id="SHOWME"></div>
</body>
</html>```

• For real fun, change the 16 in that last code to 36 and then try some ordinary words, using any letters at all. Especially try words where the letters are in alphabetical order, such as
-- abet
-- bent

Isn't that fun?

Shows the limitation of parseInt as a detection mechanism, not so incidentally.

[If you don't get it, try using the word "as". Now does it make sense?]

p.s.: You don't need to convert to upper case...parseInt handles upper/lower the same.

• Originally Posted by Old Pedant
Code:
```<p>Convert a hex, octal, binary or duodecimal value to decimal</p><br>

<form name = "myform">
Value to Convert <input type = "text" name = "inputField" onCHANGE = "calc()">
<input name=foo>  ?? What does foo do the noo?
</form>

<script type = "text/javascript">

function calc()
{
var inp = document.myform.inputField.value.toUpperCase();
var fromHex = parseInt(inp, 16);
if ( !isNaN(fromHex) ) alert ("The decimal value of " + inp + " hexadecimal is " + fromHex);
var fromOctal = parseInt(inp, 8);
if ( !isNaN(fromOctal) ) alert ("The decimal value of " + inp + " octal is " + fromOctal);
var fromDuoDecimal = parseInt(inp, 12);
if ( !isNaN(fromDuoDecimal) ) alert ("The decimal value of " + inp + " duodecimal is " + fromDuoDecimal);
var fromBinary = parseInt(inp, 2);
if ( !isNaN(fromBinary) ) alert ("The decimal value of " + inp + " binary is " + fromBinary);
}
</script>```
Thanks for the correction.

• Oops...the "foo" turned into a button in my real version. Sorry.

• Originally Posted by Old Pedant
For real fun, change the 16 in that last code to 36 and then try some ordinary words, using any letters at all. Especially try words where the letters are in alphabetical order, such as
-- abet
-- bent

Isn't that fun?

Shows the limitation of parseInt as a detection mechanism, not so incidentally.

[If you don't get it, try using the word "as". Now does it make sense?]
I don't sense why is that so fun.
From base 36 to base 10, "as" becomes 10*(36)+28=388. parseInt('as',36) returns the same 388. What's so funny?

a=10
b=11
e=14
t=29
so that:
parseInt('abet',36)=481349 // 10*(36*36*36)+11*(36*36)+14*(36)+29

That is absolutelly correct . Where do you see "limitation"?

• I assume you didn't really try my fun page there. If you had you would have seen this result for the word as:
Code:
```The decimal value of AS to the base 36 is 388
The decimal value of AS to the base 35 is 378
The decimal value of AS to the base 34 is 368
The decimal value of AS to the base 33 is 358
The decimal value of AS to the base 32 is 348
The decimal value of AS to the base 31 is 338
The decimal value of AS to the base 30 is 328
The decimal value of AS to the base 29 is 318
The decimal value of AS to the base 28 is 10  <<== LOOK AT THE CHANGE!
The decimal value of AS to the base 27 is 10
The decimal value of AS to the base 26 is 10
The decimal value of AS to the base 25 is 10
The decimal value of AS to the base 24 is 10
The decimal value of AS to the base 23 is 10
The decimal value of AS to the base 22 is 10
The decimal value of AS to the base 21 is 10
The decimal value of AS to the base 20 is 10
The decimal value of AS to the base 19 is 10
The decimal value of AS to the base 18 is 10
The decimal value of AS to the base 17 is 10
The decimal value of AS to the base 16 is 10
The decimal value of AS to the base 15 is 10
The decimal value of AS to the base 14 is 10
The decimal value of AS to the base 13 is 10
The decimal value of AS to the base 12 is 10
The decimal value of AS to the base 11 is 10```
The point is that when a letter is *NOT* in the legal set of characters for the given base, then the conversion *STOPS* at that letter but NO ERROR IS GIVEN.

Actually, this is no different than doing
Code:
`var whatever = parseInt("37 people agree");`
JavaScript will happily put the value 37 into the variable whatever and *IGNORE* all the non-numeric text that follows.

Sometimes this is an advantage. But all too often people seem to rely on parseInt and parseFloat as "validators" of text as numeric values. And of course they aren't. They only validate that the given text *starts* with a number.

In my own code, that's why if I do use one or the other to validate a form field, I put the thus validated value *BACK* into the field so the user can see what I am actually accepting.

Example:
Code:
```<script>
function validatePrice( fld )
{
var v = parseFloat( fld.value );
if ( isNaN(v) )
{
alert("Price is not a valid number");
return false;
}
fld.value = v.toString(2); // !!! *** PUT BACK A NUMBER *** !!!
return true;
}
</script>
...
<form ...>
<input name="price" onchange="validatePrice(this);">
...
</form>```
Now if the user enters 37 dollars and 17 cents into that field, it will be accepted, but it will be changed to 37.00

Okay?

• Originally Posted by Old Pedant
In my own code, that's why if I do use one or the other to validate a form field, I put the thus validated value *BACK* into the field so the user can see what I am actually accepting.

Example:
Code:
```<script>
function validatePrice( fld )
{
var v = parseFloat( fld.value );
if ( isNaN(v) )
{
alert("Price is not a valid number");
return false;
}
fld.value = v.toString(2); // !!! *** PUT BACK A NUMBER *** !!!
return true;
}
</script>
...
<form ...>
<input name="price" onchange="validatePrice(this);">
...
</form>```
Now if the user enters 37 dollars and 17 cents into that field, it will be accepted, but it will be changed to 37.00

Okay?
Not Okay.

fld.value = v.toString(2); should read fld.value = v.toFixed(2);

And if you wish to accept only integer values (or round down to the the next whole number below) then
var v = parseFloat( fld.value ); should read var v = parseInt( fld.value );

As you say, if the user enters 37xx then parseInt() and parseInt() only verify that the value starts with a number, and ignores the rest. So 37xx returns 37. You can overcome this by using Math.floor() which returns NaN. Or another way is var v = parseInt(fld.value *1);

• Oops...typo on the toString instead of toFixed.

Actually, I would NOT rely on just parseFloat in almost all cases.

I'd probably also use a regular expression to ensure that there's no junk in the string.

I was just making the point that using parseFloat or parseInt alone is often not a good idea. And you actually helped strengthen my argument, Philip. <grin/>

Oh...and since it's a price field, of course I don't want to get only integer values. I really did mean to use parseFloat. That part I got right. <grin style="sickly" />

• Originally Posted by Old Pedant
I'd probably also use a regular expression to ensure that there's no junk in the string.
I was just making the point that using parseFloat or parseInt alone is often not a good idea.
Programming is often not a good idea

Beyond the joke now - parseInt(), parseFloat(), Number() and all the methods in javascript or other languages ... they are not good or bad ideas. They are only correctly or incorrectly understood and used. People often forget that the browser's programming interpreter has no special preference for a certain base, while humans do have a weakness for decimal base.

Why should this:
Code:
`parseInt('10px',10)// returns 10`
be more "correct" and understandable than this one?:
Code:
`parseInt('apx',11)// returns 10`
In the first case, humans guess or presume that the input value is a distance/size in pixels. This is not so obvious for humans in the second example.

The way we use a method depends on which is the nature of the input data, which is nature of the expected result and on the limitations/specifications of that method.

In the particular case of parseInt() we should, of course, test for the nature of input/output in case we can not control or we don't know the nature of the input flow. But this is a general well known programming caution and I don't sense why you expect parseIn() to make an exception.

• I don't sense why you expect parseInt() to make an exception
Because in other languages and libraries, similar functions/methods would *NOT* accept "10 bananas" as a legal number. They would give an error/exception.

I guess I am really saying I don't like the choice of functionality that the JavaScript designers made. I would much rather get NaN from parseInt("10 xyz")

My preference. Your mileage may vary.

•
Page 1 of 2 12 Last

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•