Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal to hex in Lua 4?

I found this formula to convert decimal numbers to hexadecimal color values in Lua:

http://lua-users.org/lists/lua-l/2004-09/msg00054.html

However, I have a few questions about the formula:

  1. My input needs to be normalized between 0 and 1 instead of 0 and 255. Is this a potential problem?
  2. I am stuck with Lua 4.01 instead of whatever the latest version is. I can't upgrade. Is this a problem?

Thanks!!

like image 348
posfan12 Avatar asked Dec 19 '22 16:12

posfan12


1 Answers

In Lua 5.x you can use the string.format function with the %x format specifier to convert integers to their hexadecimal representation. In your case it would look like this:

local input = 0.5
local output = string.format("%x", input * 255) -- "7F"

I don't know Lua 4.0.1 well so I can't tell you if this function is available (perhaps under a different name). That said, if its not, then you might be able to workaround by turning this into a C function that uses sscanf.

like image 76
hugomg Avatar answered Jan 06 '23 07:01

hugomg