Created
June 29, 2011 14:43
-
-
Save Yonaba/1053970 to your computer and use it in GitHub Desktop.
BinaryToDecimal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--Returns a binary string computed from a decimal arg | |
function dec2bin(dec) | |
local r,q | |
local str="" | |
repeat | |
q = math.modf(dec/2) | |
r= dec%2 | |
dec=q | |
str = str..tostring(r) | |
until (q==1) | |
str = str..tostring(q) | |
str = string.reverse(str) | |
if string.len(str) < 8 then | |
local add = 8-string.len(str) | |
while (add>0) do | |
str = "0"..str | |
add = add-1 | |
end | |
end | |
return str | |
end | |
--Returns decimal number from binary string | |
function bin2dec(bin) | |
local t={} | |
local dec = 0 | |
for i = 1,8,1 do | |
t[i] = tonumber(string.sub(bin,i,i)) | |
end | |
for i=8,1,-1 do | |
if t[i] then dec = dec + t[i]*math.pow(2,(8-i)) end | |
end | |
return dec | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment