Binary Conversion in Lua

The following Lua script converts a number from base 10 to base 2:

-- This function takes in a number and returns its binary form as a string
function toBinary(num)
	local bin = ""  -- Create an empty string to store the binary form
	local rem  -- Declare a variable to store the remainder

	-- This loop iterates over the number, dividing it by 2 and storing the remainder each time
	-- It stops when the number has been divided down to 0
	while num > 0 do
		rem = num % 2  -- Get the remainder of the division
		bin = rem .. bin  -- Add the remainder to the string (in front, since we're iterating backwards)
		num = math.floor(num / 2)  -- Divide the number by 2
	end

	return bin  -- Return the string
end

-- Example usage
toBinary(5)  -- 101

This script first defines a function, to_binary, which takes a number in base 10 as its input. The function then uses a while loop to repeatedly divide the number by 2 and store the remainder in a string, bin. Finally, the function returns the string, bin.

When run, this script will print the number 10 in base 2.

6 Likes