Skip to content

Instantly share code, notes, and snippets.

@edzillion
Last active November 19, 2023 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edzillion/018c002959386ddf9dbc100f46804015 to your computer and use it in GitHub Desktop.
Save edzillion/018c002959386ddf9dbc100f46804015 to your computer and use it in GitHub Desktop.
Lua script to convert numbers from base 10 to base 2
-- By xDeltaXen from https://devforum.roblox.com/t/binary-conversion-in-lua/1718171
-- 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment