Last active
November 19, 2023 16:47
-
-
Save edzillion/018c002959386ddf9dbc100f46804015 to your computer and use it in GitHub Desktop.
Lua script to convert numbers from base 10 to base 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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