Decimal to Binary function I made

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
iPoisonxL
Party member
Posts: 227
Joined: Wed Feb 06, 2013 3:53 am
Location: Australia
Contact:

Decimal to Binary function I made

Post by iPoisonxL »

Hi! I created a cool function that converts decimal integers to binary integers. Here it is.

Code: Select all

function toBinary(int)
	if(type(int)=="number")then
		local current = int
		local bin = {}
		while(current~=0)do
			table.insert(bin, current%2)
			current = math.floor(current / 2)
		end
		local result = ""
		for i,v in pairs(bin) do
			result = result .. v
		end
		return string.reverse(result)
	end
	return "error: string input"
end
Use it however you want, I don't care.

Here's an example
binary.lua
(428 Bytes) Downloaded 147 times

Code: Select all

      L
    L Ö
    Ö V
L Ö V E
Ö B E
V E
E Y
Website
User avatar
Roland_Yonaba
Inner party member
Posts: 1563
Joined: Tue Jun 21, 2011 6:08 pm
Location: Ouagadougou (Burkina Faso)
Contact:

Re: Decimal to Binary function I made

Post by Roland_Yonaba »

Small addendum, if you want to pad it to 8 characters, you can change the return statement to this.

Code: Select all

return ('%08s'):format(string.reverse(result))
That said, nice.
User avatar
iPoisonxL
Party member
Posts: 227
Joined: Wed Feb 06, 2013 3:53 am
Location: Australia
Contact:

Re: Decimal to Binary function I made

Post by iPoisonxL »

Roland_Yonaba wrote:Small addendum, if you want to pad it to 8 characters, you can change the return statement to this.

Code: Select all

return ('%08s'):format(string.reverse(result))
That said, nice.
Sweet thanks!

Code: Select all

      L
    L Ö
    Ö V
L Ö V E
Ö B E
V E
E Y
Website
User avatar
Ref
Party member
Posts: 702
Joined: Wed May 02, 2012 11:05 pm

Re: Decimal to Binary function I made

Post by Ref »

Could shorten a bit.

Code: Select all

function toBinary( int )
	assert( type( int ) == 'number', 'Error: Non-number input to toBinary!' )
	local current	= math.floor( int )
	local result	= ''
	while( current	~= 0 ) do
		result		= result..current % 2
		current		= math.floor( current / 2)
		end
	return ( '%08s' ):format( string.reverse( result ) )
	end
User avatar
iPoisonxL
Party member
Posts: 227
Joined: Wed Feb 06, 2013 3:53 am
Location: Australia
Contact:

Re: Decimal to Binary function I made

Post by iPoisonxL »

Ref wrote:Could shorten a bit.

Code: Select all

function toBinary( int )
	assert( type( int ) == 'number', 'Error: Non-number input to toBinary!' )
	local current	= math.floor( int )
	local result	= ''
	while( current	~= 0 ) do
		result		= result..current % 2
		current		= math.floor( current / 2)
		end
	return ( '%08s' ):format( string.reverse( result ) )
	end
That's true, thank you. Not much of a code golfer myself

Code: Select all

      L
    L Ö
    Ö V
L Ö V E
Ö B E
V E
E Y
Website
User avatar
airstruck
Party member
Posts: 650
Joined: Thu Jun 04, 2015 7:11 pm
Location: Not being time thief.

Re: Decimal to Binary function I made

Post by airstruck »

Ref wrote:Could shorten a bit.
Could just as easily shorten it with table.concat, probably better than doing all that string concatenation.

Not sure only converting to binary is very useful, might as well add the extra line or two to convert to arbitrary base.

Code: Select all

local function toBase (base, number)
    local result = {}
    
    while number > 0 do
        local digit = number % base
        result[#result + 1] = digit < 10 and digit or string.char(55 + digit)
        number = math.floor(number / base)
    end
    
    return string.reverse(table.concat(result))
end
User avatar
Positive07
Party member
Posts: 1014
Joined: Sun Aug 12, 2012 4:34 pm
Location: Argentina

Re: Decimal to Binary function I made

Post by Positive07 »

Well I have weird ways of doing things so here is my attempt at this!

Code: Select all

local hex = {
    ["0"] = "0000", ["1"] = "0001", ["2"] = "0010", ["3"] = "0011",
    ["4"] = "0100", ["5"] = "0101", ["6"] = "0110", ["7"] = "0111",
    ["8"] = "1000", ["9"] = "1001", ["A"] = "1010", ["B"] = "1011",
    ["C"] = "1100", ["D"] = "1101", ["E"] = "1110", ["F"] = "1111",
}

local func = function (n) return hex[n] end

tobinary = function (n)
    local result = string.format("%X", n):gsub("(.)", func):gsub("^(0*)(.)","%2")
    return result
end
Explanation:
  • First we format the number into an hexadecimal string
  • Second we take each character of the string, that is, each number (or letter) and pass them through a function using gsub
  • The function looks up the hexadecimal character in the lookup table and returns the binary value associated to that character
  • Lastly we trim all the leading zeros because they are not really needed
NOTE: I assign the value to the local variable result so that all the other return values provided by gsub are discarded
for i, person in ipairs(everybody) do
[tab]if not person.obey then person:setObey(true) end
end
love.system.openURL(github.com/pablomayobre)
User avatar
airstruck
Party member
Posts: 650
Joined: Thu Jun 04, 2015 7:11 pm
Location: Not being time thief.

Re: Decimal to Binary function I made

Post by airstruck »

Positive07 wrote:First we format the number into an hexadecimal string
Could use octal and cut that table in half ;)
Positive07 wrote:I assign the value to the local variable result so that all the other return values provided by gsub are discarded
You can wrap the expression in parens to get the same effect:

Code: Select all

return (string.format("%X", n):gsub("(.)", func):gsub("^(0*)(.)","%2"))
User avatar
ivan
Party member
Posts: 1911
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Decimal to Binary function I made

Post by ivan »

Funny enough binary to a number (the reverse of what you are doing) is actually much easier:

Code: Select all

decimal = tonumber(binarysz,2)
where binarysz is a string of 0s and 1s
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: Decimal to Binary function I made

Post by bartbes »

Positive07 wrote:Well I have weird ways of doing things so here is my attempt at this!
My attempt at cleaning this up (and using octal, as time thief mentioned):

Code: Select all

do
	local conv = {}

	for i = 0, 7 do
		conv[tostring(i)] = ("%d%d%d"):format(math.floor(i%8/4), math.floor(i%4/2), math.floor(i%2/1))
	end

	function tobinary(n)
		return (("%o"):format(n):gsub(".", conv):match("1.+$"))
	end
end

print(tobinary(4713))
It still doesn't strike me as efficient, though.

EDIT: I just realized the match doesn't quite work for 0, oops. (Just add 'or 0'.)
Post Reply

Who is online

Users browsing this forum: Semrush [Bot] and 62 guests