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.
Sorry, I forgot to mention, the input is actually a BigInt
and is considered to be Infinity
when using parseInt()
.
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);
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.