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:
Thanks!!
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
.
The example function demonstrated at http://lua-users.org/lists/lua-l/2004-09/msg00054.html does not converts negative numbers. Here is an example of conversion for both, negative and positive numbers:
function decimalToHex(num)
if num == 0 then
return '0'
end
local neg = false
if num < 0 then
neg = true
num = num * -1
end
local hexstr = "0123456789ABCDEF"
local result = ""
while num > 0 do
local n = math.mod(num, 16)
result = string.sub(hexstr, n + 1, n + 1) .. result
num = math.floor(num / 16)
end
if neg then
result = '-' .. result
end
return result
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.