Created
October 6, 2016 02:04
-
-
Save gkucmierz/3983688f61158465f8fa844c2b33f58a to your computer and use it in GitHub Desktop.
base conversion functions
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
| let Alphabet = { | |
| BINARY: '01', | |
| OCTAL: '01234567', | |
| DECIMAL: '0123456789', | |
| HEXA_DECIMAL: '0123456789abcdef', | |
| ALPHA_LOWER: 'abcdefghijklmnopqrstuvwxyz', | |
| ALPHA_UPPER: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', | |
| ALPHA: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', | |
| ALPHA_NUMERIC: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
| }; | |
| function convert(input, source, target) { | |
| return fromNum(toNum(input, source), target); | |
| } | |
| function toNum(inp, str) { | |
| return inp.split('').reduce((r, c, i) => { | |
| let idx = str.indexOf(c); | |
| return r + Math.pow(str.length, inp.length-i-1) * idx; | |
| }, 0); | |
| } | |
| function fromNum(inp, str) { | |
| let res = []; | |
| let base = str.length; | |
| while (inp) { | |
| let tmp = inp % base; | |
| res.unshift(str[tmp]); | |
| inp = (inp - tmp) / base; | |
| } | |
| return res.join('') || str[0]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment