Page 1 of 1

javascript for beginners ^^

Posted: Wed Nov 05, 2008 6:33 pm
by Andr3w
Hey guys,

first: I'm an absolute beginner in things like coding, crypto and so on.
But I'm very interested at all. I have basics in html and tried to learn javascript.

So i began solving the challenges a few days ago. I wrote a little hexa-deci-bin program and was able to solve some of the elementary challenges.

Just a question I didn't find an answer for in Internet:
i.e: I have a decimal number. I divide it with 2 and "save" the rest in a var named savednumber.

var input;
var savednumber;
var number;
input = prompt("Decimal number, to convert in binary system:");
number = input;
savednumber = (number % 2);
alert (savednumber)

to get the whole binary number I have to repeat this step as often as number isnt smaller than 1 or better isnt 0

var input;
var savednumber;
var number;
input = prompt("Decimal number, to convert in binary system:");
number = input;
if (number >= 1)
{savednumber = (number % 2);
alert (savednumber);
number = parseInt (number / 2);}

so far so good ... but the problem is that this program alerts a number, i have to press ok, it alerts the next number ... an so on ... it isnt ablr to present me the whole string of the binary number ...

can you help me to solve this problem ?

and if you know javascript better than me, which shouldn't be too hard you could please tell me a way (like using different variables like integers or sth. like that) to calculate with more than 20 charakters or sth like this ...

thank you

Re: javascript for beginners ^^

Posted: Wed Nov 05, 2008 7:22 pm
by tails
Hi,
Andr3w wrote:to get the whole binary number I have to repeat this step as often as number isnt smaller than 1 or better isnt 0
To do this, you can use a loop structure by using the keyword while.
Andr3w wrote:it isnt ablr to present me the whole string of the binary number ...
You can construct the resulting string in the loop, and show it after quitting the loop.

Your code will be like this:

Code: Select all

var input; 
var savednumber;
var number; 

savednumber="";
input = prompt("Decimal number, to convert in binary system:"); 
number = input; 
while (number >= 1) {
  savednumber = (number % 2) + savednumber; 
  number = parseInt(number / 2);
}
alert (savednumber); 

Posted: Wed Nov 05, 2008 10:17 pm
by Andr3w
thank you very much

do you know how to calculate longer integers with this kind of code?

Posted: Wed Nov 05, 2008 10:59 pm
by tails
Andr3w wrote:do you know how to calculate longer integers with this kind of code?
You have to represent large integers with arrays or strings. It will be a good exercise to implement such code by yourself. In practise, there are some libraries that handles long integers, so you can choose one to use.

Posted: Thu Nov 06, 2008 10:54 am
by Andr3w
thx

that was the hint i needed ...