Convert numbers to and from a custom positional notation.
Y.AnyBaseConverter is an object that will convert numbers to and from a positional notation with a custom alphabet and base.
Numbers are generally displayed in base ten. This means there are ten single-digit numbers (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) before the first two-digit number, 10. Sometimes it is useful to work with numbers in other bases. Base 2, base 8, and base 16 tend to come up frequently in programming. JavaScript provides a toString method on numbers which can convert a number to any base from base 2 to base 36 and a parseInt function for converting the strings back into numbers. For bases greater than 10, lower-case letters are used for single digits greater than 9. For example, base 16 uses these single-digit numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f.
Y.AnyBaseConverter is very similar to number.toString and parseInt except it can convert to and from bases greater than 36 and use a custom alphabet to represent the single-digit numbers. In addition to any convenient mathematical properties, it may be helpful to convert to a higher base as a simple way to compress a large number as a string or to use a custom alphabet as a method of obfuscation.
' + number + ' converts to ' + numberConverted + '
'); bodyNode.append('' + numberConverted + ' converts back to ' + anyBaseConverter.from(numberConverted) + '
'); // // Binary - Used primarily by computer hardware. // bodyNode.append('' + number + ' converts to ' + numberConverted + '
'); bodyNode.append('' + numberConverted + ' converts back to ' + anyBaseConverter.from(numberConverted) + '
'); // // Base 58 - Only uses alphanumeric digits that are easily human readable. // bodyNode.append('' + number + ' converts to ' + numberConverted + '
'); bodyNode.append('' + numberConverted + ' converts back to ' + anyBaseConverter.from(numberConverted) + '
'); // // Confusing - Same base, same characters, different order. // bodyNode.append('' + number + ' converts to ' + numberConverted + '
'); bodyNode.append('' + numberConverted + ' converts back to ' + anyBaseConverter.from(numberConverted) + '
'); // // Large Alphabet - Take care to encode characters correctly! // bodyNode.append('' + number + ' converts to ' + numberConverted + '
'); bodyNode.append('' + numberConverted + ' converts back to ' + anyBaseConverter.from(numberConverted) + '
'); }); ```This example produces the following output.
1234567890 converts to 19aWBI
19aWBI converts back to 1234567890
1234567890 converts to 1001001100101100000001011010010
1001001100101100000001011010010 converts back to 1234567890
1234567890 converts to 2t6V2H
2t6V2H converts back to 1234567890
1234567890 converts to 6413592078
6413592078 converts back to 1234567890
1234567890 converts to !!Ù¼_
!!Ù¼_ converts back to 1234567890