简体   繁体   English

在 Lua 4 中将十进制转换为十六进制?

[英]Convert decimal to hex in Lua 4?

I found this formula to convert decimal numbers to hexadecimal color values in Lua:我发现这个公式可以在 Lua 中将十进制数转换为十六进制颜色值:

http://lua-users.org/lists/lua-l/2004-09/msg00054.html 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?我的输入需要在 0 和 1 而不是 0 和 255 之间标准化。这是一个潜在的问题吗?
  2. I am stuck with Lua 4.01 instead of whatever the latest version is.我坚持使用 Lua 4.01 而不是最新版本。 I can't upgrade.我无法升级。 Is this a problem?这是一个问题吗?

Thanks!!谢谢!!

In Lua 5.x you can use the string.format function with the %x format specifier to convert integers to their hexadecimal representation.在 Lua 5.x 中,您可以使用带有%x格式说明符的 string.format 函数将整数转换为其十六进制表示。 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).我不太了解 Lua 4.0.1,所以我不能告诉你这个功能是否可用(也许用不同的名字)。 That said, if its not, then you might be able to workaround by turning this into a C function that uses sscanf .也就是说,如果不是,那么您可以通过将其转换为使用sscanf的 C 函数来解决。

The example function demonstrated at http://lua-users.org/lists/lua-l/2004-09/msg00054.html does not converts negative numbers. http://lua-users.org/lists/lua-l/2004-09/msg00054.html中演示的示例函数不会转换负数。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM