从基础10初学者转换

时间:2014-08-25 02:51:29

标签: javascript base

我被要求编写有助于从基地10到任何其他基地的代码。到目前为止我有这个

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)

很抱歉,如果这是基本的,我需要保持简单,感谢您的帮助

2 个答案:

答案 0 :(得分:2)

使用以下代码:

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));

请参阅此jsfiddle:http://jsfiddle.net/jondinham/mLz5ycey

答案 1 :(得分: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

您甚至可以将其附加到数字原型以获得额外的乐趣。

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

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

但请注意,这仅适用于∀n∈ℤ,n≥0。演示:http://jsfiddle.net/DerekL/nxf6wpkz/


  

为什么数学家声称万圣节和圣诞节一样?

     

因为convertToBase(25, 8)

     
    

10月31日= 12月25日