3

So this is an outrage, a simple equation results in a random number that I can make little sense of.

Ok, so I am trying to make an app that converts from Binary to Base Ten. I know one way of doing this is to do this.

Say, 11001 to base ten.

Take the left-most digit: 1

0 * 2 + 1(This 1 is the leftmost binary digit) = 1...
1 * 2 + 1(This 1 is the second leftmost binary digit) = 3...
3 * 2 + 0(etc...) = 6...
6 * 2 + 0 = 12...
12 * 2 + 1 = 25...

So, that correctly converts into 25. Although, when I plug that equation with variables in JavaScript, it turns out random crap.

Watch:

Inputarray is an array of all the characters in the number the user inputted. So, if 11010, then inputarray is 1,1,0,1,0.

Then it loops over each character of the array and plugs each number into the equation as shown.

for (var j=0;j<=uinputlen;j++) {
var nextletter = uinput.charAt(j);
inputarray.push(nextletter);
}

for (var h=0;h<=uinputlen;h++) {
decvalue = decvalue * 2 + inputarray[h];
}

BTW, "decvalue" is preset to 0 at the beginning of my code.

Please comment on any questions on the description or anything else, it is kind of confusing.

j08691
  • 204,283
  • 31
  • 260
  • 272
austinstout
  • 1,180
  • 1
  • 11
  • 14

3 Answers3

3

JavaScript can do this natively:

var binary = "11001";
var decimal = parseInt(binary,2);

// other way:

var decimal = 1234;
var binary = decimal.toString(2);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

You are adding a character code, not the value digit represents. .charAt() will return '0' or '1' which is a string and, therefore, it will be added as a string.

I suggest you change how you push values to the following:

inputarray.push(nextletter == '1' ? 1 : 0)

or

inputarray.push(nextletter * 1)
Krizz
  • 11,362
  • 1
  • 30
  • 43
  • charAt returns the string at that position, and adding a number to a string concatenates, it doesn't convert to the char code. – Jim Deville Jan 02 '13 at 21:28
0

Since you are getting characters in your input array, JavaScript is converting the result to strings:

var a = 0; a = a * 2 + '1'; alert(a); //alerts "01"

In order to get your desired behavior, you need to cast the string:

var a = 0; a = a * 2 + Number('1'); alert(a); //alerts 1

In general, there are better ways to do this though, (such as @Kolink's answer)

See http://www.quirksmode.org/js/strings.html#stringnum for more information.

Jim Deville
  • 10,632
  • 1
  • 37
  • 47