Skip to content

Instantly share code, notes, and snippets.

@wizard04wsu
Last active July 30, 2022 19:45
Show Gist options
  • Save wizard04wsu/8827255 to your computer and use it in GitHub Desktop.
Save wizard04wsu/8827255 to your computer and use it in GitHub Desktop.
Convert a number to a different base (e.g., from hex to decimal)
//Convert a number to a different base (e.g., from hex to decimal).
//Returns a string representation of the number, or NaN if `num` does not represent a number of the specified base.
function changeBase(num, fromRadix, toRadix){
if(!(1*fromRadix) || fromRadix%1 !== 0 || fromRadix < 2 || fromRadix > 36){
throw new RangeError(`'fromRadix' must be an integer between 2 and 36, inclusive.`);
}
if(!(1*toRadix) || toRadix%1 !== 0 || toRadix < 2 || toRadix > 36){
throw new RangeError(`'toRadix' must be an integer between 2 and 36, inclusive.`);
}
num = (""+num).toUpperCase();
//convert the number to decimal (BigInt)
let symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".slice(0, fromRadix),
rxp = new RegExp(`^([${symbols}]*)(?:\\.([${symbols}]*))?$`),
matches = rxp.exec(num);
if(!matches || num == ".") return NaN; //`num` is not a number of the specified base
let integer = matches[1] || "0",
fraction = matches[2];
integer = parseBigInt(integer, fromRadix);
if(fraction) fraction = parseBigInt(fraction, fromRadix);
//convert the decimal number to desired base
return integer.toString(toRadix) + (fraction ? "."+fraction.toString(toRadix) : "");
}
function parseBigInt(string, radix){
if(!(1*radix) || radix%1 !== 0 || radix < 2 || radix > 36){
throw new RangeError(`'radix' must be an integer between 2 and 36, inclusive.`);
}
string = ""+string;
let symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".slice(0, radix);
if(!RegExp(`^[${symbols}]+$`, "i").test(string)) return NaN; //`string` does not represent a number of the specified base
radix = BigInt(radix);
return [...string].reduce((result, currentDigit)=>(result*radix + BigInt(symbols.indexOf(currentDigit))), 0n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment