var Stack = (function(){ var items = new WeakMap(); //先入后出,后入先出 class Stack{ constructor(){ items.set(this,[]); } push(ele){ //入栈 var ls = items.get(this); ls.push(ele); } pop(){ //出栈 var ls = items.get(this); return ls.pop(); } size(){ //获取栈的长度 var ls = items.get(this); return ls.length; } print(){ //打印栈 var ls = items.get(this); return ls.toString(); } } return Stack; })(); /** * num 需要转化的数字 * base 转化的进制,默认为 2 * */ function devide(num,base){ base = Math.floor(base) || 2; if(typeof num != "number" || num < 0 || base > 16 || base < 2){ throw new Error("参数错误"); return ''; } num = Math.floor(num); var code = "0123456789ABCDEF"; var stack = new Stack(); var res = ''; var rem; while(num > 0){ rem = num % base; stack.push(rem); num = Math.floor(num/base); } while(stack.size() > 0){ res += code[stack.pop()]; } return res; } console.log(devide(15,16))
任意进制转十进制
function transfrom(num,base){ //任意进制转十进制 var bases = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"]; var config = {}; for(var k = 0; k < base; k++){ config[bases[k]] = k; } num = String(num); num = num.toUpperCase(); var count = 0; var res = 0; var i; while(num.length > 0){ i = num[num.length - 1]; i = config[i]; res = res + i * Math.pow(base,count); num = num.substr(0,num.length-1); count++; } return res; } console.log(transfrom('ff',16)); console.log(transfrom('11',2));