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.
(A lua only question)
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
- nevon
- Commander of the Circuloids
- Posts: 938
- Joined: Thu Feb 14, 2008 8:25 pm
- Location: Stockholm, Sweden
- Contact:
Re: (A lua only question)
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
- bartbes
- Sex machine
- Posts: 4946
- Joined: Fri Aug 29, 2008 10:35 am
- Location: The Netherlands
- Contact:
Re: (A lua only question)
Code: Select all
tonumber("11000100", 2) --> 196
Re: (A lua only question)
Even better. Can easily go to octal and hexidecimal.
Who is online
Users browsing this forum: Google [Bot], Semrush [Bot] and 59 guests