0

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?

vanowm
  • 9,466
  • 2
  • 21
  • 37
  • On each iteration, you get a digit via `%` and then divide the number by the base. Repeat until the number is 0. You don't have to compute the "count" as in your current code. – Pointy Aug 11 '22 at 15:02
  • [This answer](https://stackoverflow.com/a/32480941) isn't exactly what you need, but I think it can give you the correct results and would just need to be modified for your use case. – EssXTee Aug 11 '22 at 15:04

3 Answers3

3

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;
}
vanowm
  • 9,466
  • 2
  • 21
  • 37
1

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;
}
Konrad
  • 21,590
  • 4
  • 28
  • 64
0

Just in case someone is looking for the encoding/decoding solution:

const numBase = (() =>
{
  //base65
  let baseData = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY=+/-";
  return {
    get base() {return baseData;},
    set base(data) {baseData = data;},
    to: (num, radix = baseData.length) =>
    {
      let result = "";
      for(; num > 0; num = ~~(num / radix))
        result = baseData[num % radix] + result;

      return result || "0";
    },
    from: (text, redix = baseData.length) =>
    {
      let result = 0;
      for(let i = text.length, x = 1; --i >= 0; x *= redix)
        result += baseData.indexOf(text[i]) * x;

      return result;
    }
  };
})();

const redix = 65;
for(let i = 0; i < 4097; i += 82)
{
  console.log(i, "⟶", numBase.to(i, redix), "⟶", numBase.from(numBase.to(i, redix), redix));
}
.as-console-wrapper{top:0;max-height:unset!important;overflow:auto!important;}
vanowm
  • 9,466
  • 2
  • 21
  • 37