The title says it all. How can I convert a number to binary?
This can mean a bunch of different things. Do you want the string representation of it? e.g. be able to print out 1s and 0s of a given base-10 number?
2 Likes
Seen your post, took it as a challenge, and it worked. Here’s the code:
local function check(number)
local safe = math.floor(number)
if number == safe then
return 0
else
return 1
end
end
local function covertToBinary(decimal)
local binary = ""
while math.floor(tonumber(decimal)) > 0 do
local num = decimal / 2
decimal = math.floor(num)
binary ..= check(num)
end
if math.floor(tonumber(decimal)) == 0 then
binary = string.reverse(binary)
end
return binary
end
print(covertToBinary(100)) -- 1100100
Not sure if it’ll work on numbers that have decimals in them
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.