(A lua only question)

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Evil_Bartek
Prole
Posts: 43
Joined: Sun Dec 25, 2011 5:13 pm

(A lua only question)

Post by Evil_Bartek »

I made a dec to binary converter a while ago and i want to convert it back.
So i thought of this method:

the binary is 11000100
The rightmost digit represents how many 1s (in this example 0)
The next digit left represents how many 2s (in this example 0)
The next digit left represents how many 4s (in this example 1)
The next digit left represents how many 8s (in this example 0)
The next digit left represents how many 16s (in this example 0)
The next digit left represents how many 32s (in this example 0)
The next digit left represents how many 64s (in this example 1)
The next digit left represents how many 128s (in this example 1)

then you add: 4+64+128 = 196 which is right.

Any idea how to do that in lua?
I know how to get the love2d stuff done.
User avatar
nevon
Commander of the Circuloids
Posts: 938
Joined: Thu Feb 14, 2008 8:25 pm
Location: Stockholm, Sweden
Contact:

Re: (A lua only question)

Post by nevon »

Code: Select all

function Bin2Dec(s)
    local num = 0
    local ex = string.len(s) - 1
    local l = 0
    
    l = ex + 1
    for i = 1, l do
        b = string.sub(s, i, i)
        if b == "1" then
            num = num + 2^ex
        end
        ex = ex - 1
    end
    
    return string.format("%u", num)
    
end
Source
User avatar
MarekkPie
Inner party member
Posts: 587
Joined: Wed Dec 28, 2011 4:48 pm
Contact:

Re: (A lua only question)

Post by MarekkPie »

Beat me to it.
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: (A lua only question)

Post by bartbes »

Code: Select all

tonumber("11000100", 2) --> 196
User avatar
MarekkPie
Inner party member
Posts: 587
Joined: Wed Dec 28, 2011 4:48 pm
Contact:

Re: (A lua only question)

Post by MarekkPie »

Even better. Can easily go to octal and hexidecimal.
Post Reply

Who is online

Users browsing this forum: Google [Bot], Semrush [Bot] and 59 guests