user12537794
user12537794

Reputation:

How to undo the "toString()" function

JavaScript's toString function has 1 parameter: the base. If I use (2), then the output string will be in binary, (16) -> hex, (8) -> octal. These aren't the only bases it supports; it supports up to base 36.

1234567890n.toString(36)

The result of that expression is:

kf12oi

Since this is a pure unary function that doesn't result in data lost, I was guessing there is a way to undo it too, right?

I'm trying not to use the number prefixes such as 0b, 0x, or 0o, since they don't cover everything.

If the answer isn't cross compatible, it's still acceptable.

Update

Sorry, I forgot to mention, the input is actually a BigInt and is considered to be Infinity when using parseInt().

Upvotes: 1

Views: 216

Answers (2)

Washington Guedes
Washington Guedes

Reputation: 4365

Just parse the number back with:

parseInt('kf12oi', 36); // 1234567890

If the number can't fit in the Number type. You should manually convert the number:

parseBigInt = (value = '0', base = 10) => [].reduce.call(value,
  (acc, x) => acc * BigInt(base) + BigInt(parseInt(x, base)), 0n);

valB10 = '1' + [...new Array(600)].map(x => Math.random() * 10 | 0).join('');
console.log('%s', BigInt(valB10));

valB36 = BigInt(valB10).toString(36);
console.log(valB36);

parsed = parseBigInt(valB36, 36);
console.log('%s', parsed);

console.log(BigInt(valB10) === parsed);

Upvotes: 4

Yanjan. Kaf.
Yanjan. Kaf.

Reputation: 1725

use parseInt to convert any radical number to the decimal

let num = 23;

let inBinary = num.toString(2);

console.log(inBinary);

let backtoDecimal = parseInt(inBinary, 2)

console.log(backtoDecimal)

Upvotes: 1

Related Questions