Basic Lua Converter

I need a basic conversion function for Lua. I need to convert from base 10 to base 2,3,4,5,6,7,8,9,10,11 ... 36 how can I do this?

+6
lua
source share
2 answers

In the direction of string to number , the tonumber() function takes an optional second argument, which indicates the base to use, which can be from 2 to 36 with an obvious value for digits in the bases greater than 10.

In the direction of the number to the lines, this can be done a little more effectively than Nicholas's answer in approximately the following way:

 local floor, insert = math.floor, table.insert
 function basen (n, b)
     n = floor (n)
     if not b or b == 10 then return tostring (n) end
     local digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     local t = {}
     local sign = ""
     if n <0 then
         sign = "-"
     n = -n
     end
     repeat
         local d = (n% b) + 1
         n = floor (n / b)
         insert (t, 1, digits: sub (d, d))
     until n == 0
     return sign .. table.concat (t, "")
 end

This creates fewer garbage lines to collect using table.concat() instead of calling the string concatenation operator repeatedly .. Although this is not very practical for small lines, this idiom should be studied, because otherwise, building a buffer in a loop with a concatenation operator will tend to have O (n 2 ) table.concat() , and table.concat() were designed to do much better.

The question remains unanswered whether it is more efficient to output the numbers on the stack in table t with calls to table.insert(t,1,digit) or add them to the end with t[#t+1]=digit , and then call string.reverse() to put the numbers in the correct order. I will leave the benchmarking student. Please note that although the code I pasted here is running and appears to be getting the correct answers, there may be other possibilities for changing it further.

For example, the general case of base 10 is selected and handled by the built-in tostring() function. But similar culling can be done for bases 8 and 16, which have conversion specifiers for string.format() ( "%o" and "%x" , respectively).

In addition, neither the Nikolaus solution nor my pen handles non-integer numbers very well. I emphasize that here, forcing the value of n integer with math.floor() at the beginning.

The correct conversion of the total floating-point value to any base (even base 10) is fraught with subtleties, which I leave as an exercise for the reader.

+14
source share

you can use a loop to convert the whole to a string containing the desired base. for bases below 10, use the following code if you need a base more than you need to add a string that converts the base result x% to a character (for example, use an array)

 x = 1234 r = "" base = 8 while x > 0 do r = "" .. (x % base ) .. r x = math.floor(x / base) end print( r ); 
+3
source share

All Articles