簡體   English   中英

在 Lua 4 中將十進制轉換為十六進制?

[英]Convert decimal to hex in Lua 4?

我發現這個公式可以在 Lua 中將十進制數轉換為十六進制顏色值:

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

但是,我對公式有幾個問題:

  1. 我的輸入需要在 0 和 1 而不是 0 和 255 之間標准化。這是一個潛在的問題嗎?
  2. 我堅持使用 Lua 4.01 而不是最新版本。 我無法升級。 這是一個問題嗎?

謝謝!!

在 Lua 5.x 中,您可以使用帶有%x格式說明符的 string.format 函數將整數轉換為其十六進制表示。 在您的情況下,它看起來像這樣:

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

我不太了解 Lua 4.0.1,所以我不能告訴你這個功能是否可用(也許用不同的名字)。 也就是說,如果不是,那么您可以通過將其轉換為使用sscanf的 C 函數來解決。

http://lua-users.org/lists/lua-l/2004-09/msg00054.html中演示的示例函數不會轉換負數。 以下是負數和正數的轉換示例:

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