Converting a color to a hex string?

Well, I did it, friends. A little research and some applied effort and I wound up with something of my own creation:

function toInteger(color)
	return math.floor(color.r*255)*256^2+math.floor(color.g*255)*256+math.floor(color.b*255)
end

function toHex(color)
	local int = toInteger(color)
	
	local current = int
	local final = ""
	
	local hexChar = {
		"A", "B", "C", "D", "E", "F"
	}
	
	repeat local remainder = current % 16
		local char = tostring(remainder)
		
		if remainder >= 10 then
			char = hexChar[1 + remainder - 10]
		end
		
		current = math.floor(current/16)
		final = final..char
	until current <= 0
	
	return "#"..string.reverse(final)
end

print(toHex(Color3.fromRGB(255, 125, 0)))
-- #FF7D00

Proof of concept: #ff7d00 Color Hex

16 Likes