Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i convert binary to decimal (LUA)

Tags:

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)

like image 472
Di1997 Avatar asked Sep 01 '26 15:09

Di1997


2 Answers

In Lua 5.3, tonumber works just fine:

Lua 5.3.2  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> tonumber("1000100110100011111010101001001001001100100101",2)
37834277032741
> tonumber("10010011001100011001011110001100000110110101100",2)
80920602611116
like image 54
lhf Avatar answered Sep 03 '26 17:09

lhf


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)
like image 44
Piglet Avatar answered Sep 03 '26 19:09

Piglet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!