Worth converting RGB to HEX to save?

I’m wondering if it’s worth using a function to convert RGB values into a HEX value in order to save a color. HEX would use less characters than RGB, and thus use up less of the data store cap, but not sure if it’s worth doing this in the long run, or if there are any reliable functions out there for converting RGB?

1 Like

Depends on the work you do to convert every time you serialize/deserialize and whether you think it’s worth in the long run. I would say so since it doesn’t seem computationally expensive anyways.

I made a Roblox Lua version of a GitHub open source script that converts RGB to HEX by accepting a Color3.fromRGB parameter.

Function
local values = {“R”, “G”, “B”}
local function rgbToHex(rgb)
	local hexadecimal = '0X'

	for _, colorvalue in ipairs(values) do
        local value = rgb[colorvalue]
		local hex = ''

		while(value > 0)do
			local index = math.fmod(value, 16) + 1
			value = math.floor(value / 16)
			hex = string.sub('0123456789ABCDEF', index, index) .. hex			
		end

		if(string.len(hex) == 0)then
			hex = '00'

		elseif(string.len(hex) == 1)then
			hex = '0' .. hex
		end

		hexadecimal = hexadecimal .. hex
	end

	return hexadecimal
end
2 Likes

Depends entirely on your use case. If you just want to compress data as much as possible but still be able to save colors with full color depth, I’d personally use BitBuffer and just write the 3x8 bits = 3 bytes per color. That’s equivalent to 3 characters if you were to store it as a string (which BitBuffer lets you do).

If you stored the HEX versions of the color as a string it’d be “0xBEEEEF” = 8 chars, and if you tried to store the decimal RGB versions of the colors… that’d be bad. Most of the decimal expansions are like “0.81176470588235”, or 16 chars PER CHANNEL, so like 48 chars per color. It’d be much better to store them as ints between 0-255, so you’d have 9 chars per color.

If you’re okay with storing at most 64 colors you could put them in a look-up table and store the keys in a single Base64 char. Or 64^2=4096 colors with 2 chars.

If you turned them into a single number representing every colour from 1 to 16,777,216, you could store it in radix 64 with just 4 characters.

You’d get the integer:
local rgb = 65536 * color.r + 256 * color.g + color.b
And then convert it to base 64.

This could end up saving you 5-7 characters on RGB, and 2-3 characters on Hex depending whether you had commas or the hash symbol on those. So it could easily double your available space compared to RGB.

If you want a couple functions for converting an integer to radix 64 and back again, I can grab those for you from my PC later today as I use it a lot in my storage system for a city building game where coordinates, size, number of citizens, etc is all stored in a base 64 system.