Last active
August 11, 2023 10:07
-
-
Save ryasmi/91d7fd30710264affeb9 to your computer and use it in GitHub Desktop.
Moved to https://github.com/ryasmi/baseroo - Converts a number represented as a string from one base to another (up to 64).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convertBase(value, from_base, to_base) { | |
var range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split(''); | |
var from_range = range.slice(0, from_base); | |
var to_range = range.slice(0, to_base); | |
var dec_value = value.split('').reverse().reduce(function (carry, digit, index) { | |
if (from_range.indexOf(digit) === -1) throw new Error('Invalid digit `'+digit+'` for base '+from_base+'.'); | |
return carry += from_range.indexOf(digit) * (Math.pow(from_base, index)); | |
}, 0); | |
var new_value = ''; | |
while (dec_value > 0) { | |
new_value = to_range[dec_value % to_base] + new_value; | |
dec_value = (dec_value - (dec_value % to_base)) / to_base; | |
} | |
return new_value || '0'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now supports floats ryasmi/baseroo#37