Page 1 of 3

Decimal to Binary function I made

Posted: Wed Dec 18, 2013 12:56 am
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 165 times

Re: Decimal to Binary function I made

Posted: Wed Dec 18, 2013 7:13 am
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.

Re: Decimal to Binary function I made

Posted: Wed Jul 01, 2015 8:20 am
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!

Re: Decimal to Binary function I made

Posted: Wed Jul 01, 2015 3:29 pm
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

Re: Decimal to Binary function I made

Posted: Wed Jul 15, 2015 3:09 am
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

Re: Decimal to Binary function I made

Posted: Wed Jul 15, 2015 4:30 am
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

Re: Decimal to Binary function I made

Posted: Thu Jul 16, 2015 3:41 am
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

Re: Decimal to Binary function I made

Posted: Thu Jul 16, 2015 5:53 am
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"))

Re: Decimal to Binary function I made

Posted: Thu Jul 16, 2015 7:31 am
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

Re: Decimal to Binary function I made

Posted: Thu Jul 16, 2015 9:20 am
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'.)