posfan12
posfan12

Reputation: 2651

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!!

Upvotes: 10

Views: 57970

Answers (3)

donaks
donaks

Reputation: 11

Example with converting negative dec to positive hex.

local input = -0.5
local output = string.format("%x", math.floor(input * 255)):sub(-2) -- 80

If you need to convert a non-two-digit hex number, change the string.sub argument. For Lua 4.01:

local input = -0.5
local output = strsub(format("%x", floor(input * 255)), -2) -- 80

Upvotes: 1

Andrushenko Alexander
Andrushenko Alexander

Reputation: 1973

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

Upvotes: 0

hugomg
hugomg

Reputation: 69954

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.

Upvotes: 20

Related Questions