Search code examples
lua

How do i convert binary to decimal (LUA)


I know that there's tonumber() function, but the problem is that i need to convert larger numbers like 1000100110100011111010101001001001001100100101 . I can write that by myself, but is there a way to integrate that in function? And if I write that in current function, it returns different number. For example: through wolfram alpha, I converted "Something" (base 36) to binary and got 10010011001100011001011110001100000110110101100. If I put that in my custom function and convert back to base 36, I get 1Z141Z3 or 4294967295 (range for unassigned int)


Solution

  • Lua supports 64bit integers since 5.3. Is your Lua up to date?

    Open http://www.lua.org/cgi-bin/demo and execute this quick and dirty conversion. The result matches your quoted Wolfram Alpha number.

    local dec = 80920602611116
    
    local bin = "10010011001100011001011110001100000110110101100"
    
    bin = string.reverse(bin)
    local sum = 0
    
    for i = 1, string.len(bin) do
      num = string.sub(bin, i,i) == "1" and 1 or 0
    sum = sum + num * math.pow(2, i-1)
    
    end
    
    print(sum)