I'm trying convert a number into string using nn base. Basically, trying re-create Number.toString(nn)
Here is the code I have so far which produces incorrect result:
const baseData = "0123456789abcdef";
for(let i = 0; i < 257; i += 8)
{
console.log(i, "expected:", i.toString(16), "| actual:", toBase(i, 16));
}
function toBase(n, radix)
{
let result = "";
const count = ~~(n / radix);
for(let i = 0; i < count; i++)
{
result += baseData[~~(i % radix)];
}
result += baseData[~~(n % radix)];
return result;
}
.as-console-wrapper{top:0;max-height:unset!important;overflow:auto!important;}
There must be some kind of formula for this...
Any suggestions?
const baseData = "0123456789abcdef";
for(let i = 0; i < 257; i += 8)
{
console.log(i, "expected:", i.toString(16), "| actual:", toBase(i, 16));
}
function toBase(n, radix)
{
let result = "";
while(n>0){
result = baseData[n % radix]+result;
n=(n - n % radix)/radix;
}
return result;
}
const baseData = "0123456789abcdef";
for (let i = 0; i < 257; i += 8) {
console.log(i, "expected:", i.toString(16), "| actual:", toBase(i, 16));
}
function toBase(n, radix) {
if (n === 0) return 0
const chars = '0123456789abcdef'
const result = []
while (n > 0) {
const mod = n % radix
result.unshift(chars[mod])
n = Math.floor(n / radix)
}
return result.join('')
}
.as-console-wrapper {
top: 0;
max-height: unset!important;
overflow: auto!important;
}