-2

I was asked to write code that helps to go from base 10 to any other base. So far I have this

var y=23 //Number in base 10 I want to convert
var x=2 //Base I want to convert to 
var r=[]
if(y>=x){
r.push(y%x)
var y=(Math.floor(y/x))
}
else {
r.push(y)    
}
console.log(r)

Sorry if this is to basic i need to keep it simple thanks for the help

j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

2

Use these codes:

var digits = [
  '0','1','2','3','4','5','6','7','8','9',
  'A','B','C','D','E','F','G','H','I','J',
  'K','L','M','N','O','P','Q','R','S','T',
  'U','V','W','X','Y','Z'
];

/**
 * x is the base, y is the decimal value
 * x must be in the range of 2..36
 * y must be greater than zero
 */
function base10ToBaseN(x,y) {
  var str = "";

  while (y>0) {
    var mod = y%x;
    var div = Math.floor(y/x);

    str = digits[mod]+str;
    y   = div;
  }

  return str;
}

alert(base10ToBaseN(2,23));

See this jsfiddle: http://jsfiddle.net/jondinham/mLz5ycey

jondinham
  • 8,271
  • 17
  • 80
  • 137
  • You don't need the `""` there since digits are already strings. – slebetman Aug 25 '14 at 03:27
  • ah yeah! they r already strings – jondinham Aug 25 '14 at 03:28
  • Rather than documenting it in a comment it's better to use the variable names: `base` and `number` - it allows you to delete the comment and as a bonus makes the code much more readable. – slebetman Aug 25 '14 at 03:28
  • the OP is using these x,y variables :) – jondinham Aug 25 '14 at 03:29
  • This fails where the number is 0 (it returns an empty string), consider changing the last line to something like `return str.length? str : '0';`. It also fails for negative numbers. – RobG Aug 25 '14 at 04:12
  • @RobG, i know, but i noted that in the comment before the function declaration – jondinham Aug 25 '14 at 04:15
  • 1
    @JonDinham—it's pretty easy to fix though—store the sign and treat as +ve, then put the sign back at the end. I've given you the fix for the other. – RobG Aug 25 '14 at 04:32
0
function convertToBase(input, base){
    var digits = [];
    while(digits.push(letter(input%base)), input = (input/base)|0)     //work for int
    function letter(n){ return n > 9 ? String.fromCharCode(n%base+55) : n;}
    return digits.reverse().join("");
}

convertToBase(255,16);        //FF
convertToBase(255,2);         //11111111

You can even attach this to the Number prototype for extra fun.

Number.prototype._ = function(b){ return convertToBase(this, b); };

255.._(16);       //FF
255.._(2);        //11111111
//Doesn't look like JavaScript's syntax anymore :)

However note that this only work for ∀n ∈ ℤ, n ≥ 0. Demo: http://jsfiddle.net/DerekL/nxf6wpkz/


Why do mathematicians claim that Halloween is the same as Christmas?

Because convertToBase(25, 8).

Oct 31 = Dec 25

Community
  • 1
  • 1
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • a short way of coding that is convertToBase=Function.call.bind((0).toString); – dandavis Aug 25 '14 at 03:28
  • @dandavis - OP said `toString` cannot be used. – Derek 朕會功夫 Aug 25 '14 at 03:33
  • i see that, now. was wondering why we were re-inventing the wheel... – dandavis Aug 25 '14 at 03:41
  • Regarding `+this`, given that the method is on *Number.prototype*, in what case would *this* not be a number? And even if its *this* is set to a string (using *call*, *apply* or *bind*), then the internal operations convert it to a number anyway even if *input* and *base* are both strings (and *b* is not explicitly converted to a number anyway). :-) – RobG Aug 25 '14 at 04:03
  • @RobG - `this` cannot be a primitive, so it is never a number [primitive], which might cause problem if the number is 0, though `(input/base)|0` will probably change it to a real primitive. – Derek 朕會功夫 Aug 25 '14 at 04:04
  • @Derek朕會功夫— *this* can be a primitive for built–in methods, e.g. `7..toString(2)` works just fine. In strict mode *this* can be any value for native functions too (but that's not relevant here). – RobG Aug 25 '14 at 04:09
  • @RobG - no, `this` can't be primitive anyhow. See this http://jsfiddle.net/DerekL/sokpntwe/ – Derek 朕會功夫 Aug 25 '14 at 04:12
  • @Derek朕會功夫—it can be, hence [*ECMA-262*](http://ecma-international.org/ecma-262/5.1/#sec-15.7.4.2) says "*[Number.prototype.toString] throws a TypeError exception if its this value is not a Number or a Number object*", in other words, there is no compulsion for implementations to use a Number object for *this*, though they can if they wish. – RobG Aug 25 '14 at 04:18
  • @RobG - The spec also states that primitives are immutable, so no function can be attached to it. `this` is referring to the [execution context](http://www.ecma-international.org/ecma-262/5.1/#sec-10.3), and only objects can have properties. When `this` is set to a primitive, the value must be wrapped by an object to attach the function. – Derek 朕會功夫 Aug 25 '14 at 04:27
  • @Derek朕會功夫— *this* is one parameter of an [*execution context*](http://ecma-international.org/ecma-262/5.1/#sec-10.4). In strict mode, *this* doesn't have to be an object. Try your fiddle code in strict mode, it returns *number*. When a method is called on a primitive, what's the point of converting it to an object? It's only there to provide a value, so if converted to an object, it will just be turned back into a primitive (e.g. using *valueOf*). Hence built–ins are often happy with *this* as a primitive (e.g. `Number.prototype.toString.call(7, 2)`). – RobG Aug 25 '14 at 04:49
  • @RobG - True, but that only applies to strict mode (or maybe future ECMAScript versions.) Currently, without doing `"use strict"` there is no way to make `this` a type other than object. (I do agree that wrapping primitive with a wrapper object is very unnecessary. The first time I realized `this` cannot be a primitive sounded ridiculous to me.) – Derek 朕會功夫 Aug 25 '14 at 04:59