Base Changer Module

I spent this afternoon making a ModuleScript for changing numbers between different bases. It has two functions, with two arguments each:
toDecimal(string num, number base), returns number
toBase(number num, number base), returns string representation of num converted to base base.

Currently it supports up to base 62, but can be modified to support more.

The module also supports decimals; for instance, toDecimal(“1.1”, 36) returns 1.0277777777778 (actual value: ~ 1.02777777777777767909128669). This includes toBase as well, and it avoids rounding to the best of its ability; 1.1 to base 36 takes over a hundred cycles as a result and returns an extremely long string (1.3llllllllly0u06jymdk0r8dlsejv9st8407o1jkyg65xjj9r9qrcb03thsh72ugs48wdw5z942xyywf1rx3a0j7v0ux57tyyaiuujaf9zi8rris9beu5384q1couqlqdrxdjskr7qbb3dos1q1omn9bbma71x1kua0hfi6x7a57ht82ax6bsf2b143l6iquephyu4s5onheo1p) that perfectly translates, from my testing, back to 1.1.

I made this so I could convert large number-keyed tables to string-keyed tables, shortening the keys and making them easier to manipulate manually (since it takes up less space in the code editor window) however it can also be used as a universal converter between bases by first passing the input number through toDecimal and then back through toBase as your desired base.

I’m curious what other uses y’all might find for this.

4 Likes

thanks this is really useful for datastores and such

Oh cool! You should allow for custom alphabets that can be specified.

Also if I understand correctly, converting large numbered keys in tables [i.e. 9.2e+15] to string-based large numbers in higher bases will actually take up more space than just using numbers. The particular reason behind this is because numbers will always take up 8 bytes in Roblox regardless of size (8 bytes is the equivalent or 8 string characters). If you’re curious on how you can research floating point numbers and the IEEE-754 standard. Your numbers on the other hand use an entire byte to store one symbol under-utilizing the bytes ability to hold 256 different states of information. I’m not recommending you try to account for this in this library as you will loose the gracious human readability this library provides, as well as being less efficient than binary floating point numbers. I’m simply pointing out that the specific use case you are using your library for may not be the best solution, as it unnecessarily increases the size of your keys.

Also you should add support for rational bases :smiling_imp:

EDIT: just realized this post is 6 years old